Zebra0

Learn to Program Step-by-Step

Detect if an object hit a target inside another

HitTest: Detect if an object hit another object

In this movie, instead of checking if the asteroid hit the planet, we check to see if the asteroid hit one of four boxes inside the planet. This solves the problem of the asteroid looking like it is not really hitting the planet, but also lets us change direction based on whether it hit leftEdge, rightEdge, topEdge or bottonEdge, similar to the way that we can bounce of the edges of the stage. The 4 boxes are visible in this movie, but you would set alpha to 0 for all of them.

hitting rigthEdge

Get Adobe Flash playerThe movie has a function called hitPlanet:

var numHits:int=0;
function planetHit(): void {
	planet.rotation+=3;
	numHits++;
	lblHits.text=""+numHits;
	if(numHits>=100) {
		lblHits.text="game over "+numHits; //etc.
	} //100 hits
} //planetHit

When an asteroid hits the planet we call the function in the main movie:

The code for Asteroid2.as no longer rotates the planet, but rather calls this function:

if(this.hitTestObject(MovieClip(root).planet.topEdge) || this.hitTestObject(MovieClip(root).planet.bottomEdge)) {
   dy*=-1;
   this.y+=dy; //nudge it away so this event doesn't happen again immediately
   MovieClip(root).planetHit();
}
if(this.hitTestObject(MovieClip(root).planet.leftEdge) || this.hitTestObject(MovieClip(root).planet.rightEdge)) {
   dx*=-1;
   this.x+=dx; //nudge it away so this event doesn't happen again immediately
   MovieClip(root).planetHit();
}
(The rest of the code is the same.)
Download the movie.
INDEX, Detect if an object hit another, Detect if an object hit a target inside another, Catch a Falling Star Game, Add a paddle, Add code to movie for hit and miss, Modify FallingStar to hit and miss, Add code to move the paddle