Hey Guys,
I just started trying to learn AS3 and I am getting an error that I can’t seem to fix or work around.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at code::Character()
at code::Engine()
I think it is because of the:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleaseHandler);
But I am not sure how else to grab key presses in AS3
Here is my code:
Engine.as
package code {
import flash.display.MovieClip;
import flash.display.Stage;
public class Engine extends MovieClip {
public function Engine() {
// constructor code
//Creating object of the character from the Character Class
var ourChar:Character = new Character();
//Adding the character to the stage
stage.addChild(ourChar);
//Setting the characters position
ourChar.y = stage.stageHeight / 2;
ourChar.x = stage.stageWidth / 2;
}
}
}
Character.as
package code {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Character extends MovieClip {
//Setting Movement Buttons
private var w:Boolean = false;
private var a:Boolean = false;
private var s:Boolean = false;
private var d:Boolean = false;
//Setting Movement Variables
private var speed:Number = 10;
//Detecting Degree of mouse depending on tank position
private var am:Number = mouseY - y;
private var bm:Number = mouseX - x;
private var radiansm:Number = Math.atan2(am, bm);
private var degreesm:Number = radiansm / (Math.PI / 180);
public function Character() {
// constructor code
addEventListener(Event.ENTER_FRAME,enterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleaseHandler);
}
public function enterFrameHandler(event:Event) {
if (a && !d){
this.x -= speed ;
}
if (d && !a){
this.x += speed ;
}
if (w && !s){
this.y -= speed;
}
if (s && !w){
this.y += speed;
}
}
public function keyPressHandler(event:KeyboardEvent):void{
//A = 65
//D = 68
//S = 83
//W = 87
switch(event.keyCode){
case 87:
w = true;
break;
case 65:
a = true;
break;
case 83:
s = true;
break;
case 68:
d = true;
break;
}
}
public function keyReleaseHandler(event:KeyboardEvent):void{
switch(event.keyCode){
case 87:
w = false;
break;
case 65:
a = false;
break;
case 83:
s = false;
break;
case 68:
d = false;
break;
}
}
}
}
Any help would be great!
Thanks!