I’m writing a game and it has enemies and bullets. When a bullet hits an enemy, I want to destroy the enemy and the bullet. I’m using the hitTestPoint() method to test if a bullet has hit an enemy. Here’s the code in my game loop:
for each(var bullet:Bullet in this.bullets) {
for each(var enemy:Enemy in this.enemies) {
if(enemy.hitTestPoint(bullet.x, bullet.y)) {
trace("hit");
}
}
bullet.update();
}
this.bullets and this.enemies are both arrays containing objects for bullets and enemies. Here’s those two classes:
package com {
import flash.display.MovieClip;
import flash.display.Stage;
public class Bullet extends MovieClip {
private var stageRef:Stage;
public var speed:Number = 10;
public function Bullet(stage:Stage) {
this.stageRef = stage;
}
public function update() {
this.x += Math.sin((Math.PI / 180) * (360 - this.rotation)) * this.speed;
this.y += Math.cos((Math.PI / 180) * (360 - this.rotation)) * this.speed;
}
}
}
—
package com {
import flash.display.MovieClip;
import flash.display.Stage;
public class Enemy extends MovieClip {
public var speed:Number = 4;
private var stageRef:Stage;
public function Enemy(stage:Stage) {
this.stageRef = stage;
this.x = this.stageRef.stageWidth / 3;
this.y = this.stageRef.stageHeight / 2;
}
public function update() {
}
}
}
The problem is, hitTestPoint only returns true if both the x and y values of bullet and enemy are the same, rather than if the two movie clips overlap. This leads to bullets going right through enemies but it not registering as a hit. Perhaps I’m missing a bounding box?
Is there a way I can make hitTestPoint return true if the bullet hits the enemy at all rather than only if the bullet and enemy co-ordinates are the same?
Thank you!
You want hitTestObject(), not hitTestPoint()
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#hitTestObject%28%29