I am trying to make a simple as3 game, but right now stuck at collision detection. Bullets spawn on key press, birds keep spawning on timer, but no matter where I use the hittest (I tried in the createBird, after each bullet was spawned, and in Main) it simply does not register the hit or gives null object reference errors. here is the code :
ActionScript Code:
package {
import Classes.F_Bird;
import flash.display.Sprite;
import Classes.F_Bullet;
import Classes.F_Splatter;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
public class Main extends Sprite {
public var flock:Array;
public var spawnTimer:Timer;
public var shootTimer:Timer;
public var shootL:int=1;
public var shootM:int=1;
public var shootR:int=1;
public var score:int=0;
var bullet:F_Bullet;
var newBird:F_Bird;
public function Main() {
flock = new Array();
spawnTimer= new Timer(800);
spawnTimer.addEventListener(TimerEvent.TIMER, createBird);
spawnTimer.start();
spawnTimer= new Timer(900);
spawnTimer.addEventListener(TimerEvent.TIMER, allowShoot);
spawnTimer.start();
var splatter1:F_Splatter;
splatter1=new F_Splatter(100, 100);
addChild(splatter1);
stage.addEventListener(KeyboardEvent.KEY_DOWN, processKeys);
}
public function allowShoot(timerEvent:TimerEvent):void{
shootL=1
shootM=1
shootR=1
}
public function createBird(timerEvent:TimerEvent):void{
var randomY:Number = Math.floor(Math.random()*71)+20;
var newBird=new F_Bird(20, randomY) ;
flock.push( newBird);
addChild(newBird);
if (newBird!=null){
if ( bullet.hitTestObject(newBird)){
trace ("hit");
}
}
}
private function processKeys(evt:KeyboardEvent):void{
if ((evt.keyCode== Keyboard.A) && (shootL==1)){
bullet=new F_Bullet(54, 350);
addChild(bullet);
shootL=0;
}else if ((evt.keyCode==Keyboard.S) && (shootM==1)){
bullet=new F_Bullet(250, 350);
addChild(bullet);
shootM=0;
}else if ((evt.keyCode==Keyboard.D) && (shootR==1)){
bullet=new F_Bullet(450, 350);
addChild(bullet);
shootR=0;
}
}
}
}