Bullet fires perfectly in three directions, but not left - actionscript-3

I'm quite new with actionscript, and have been scrapping together a little test game to sort of get used to the language, get my feet wet. The premise behind the game is pretty average, I have a character that can move in 8 directions, can pick up several keys that are randomly placed, and open a door when he possesses a key.
The problem comes in to play with the bullet shooting. I don't know much about trigonometry, so when a key is pressed, i just use the .rotate property to turn the player. I pass the .rotate integer into my bullet class and use that to tell which direction the bullet should travel. It works perfectly for the up, down, and right movements, but when the character is facing left the bullet is created but has no velocity whatsoever, and for the life of me I cannot figure out where the error in the code is.
If someone could look over my code and help me out, I would be much appreciated. I'm sure it's something simple that I'm just missing. I know it's a bit sloppy, so if there's any other tips you want to pass on to a novice please feel free!!
Thank you so much guys.
Main Class
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.text.TextField;
public class Main extends MovieClip
{
var player:Player;
var inventory:Inventory;
var invArray:Array = new Array();
var key:_Key;
var vx:int;
var maxSpeed:int;
var key_Up:Boolean;
var key_Down:Boolean;
var key_Left:Boolean;
var key_Right:Boolean;
var maxKey:int;
var keyCount:TextField;
var keysUp:int;
var door:Door;
var doorOpen:Boolean;
var wall1:Wall;
var wall2:Wall;
var wallCollide:Boolean;
var bulletTime:int;
var bulletLimit:int;
var bulletShoot:Boolean;
static var playerRotation:int;
public function Main()
{
init();
}
public function init():void
{
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
initPlayer();
initVariables();
initInventory();
initItems();
}
public function gameLoop(e:Event):void
{
movePlayer();
collisionDetection();
bullet();
}
public function keyDownHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = true;
break;
case 38 :
key_Up = true;
break;
case 39 :
key_Right = true;
break;
case 40 :
key_Down = true;
break;
case 32:
if(bulletShoot)
{
bulletShoot = false;
var newBullet:Bullet = new Bullet(player.rotation);
newBullet.x = player.x;
newBullet.y = player.y;
addChild(newBullet);
}
}
}
public function keyUpHandler(e:KeyboardEvent):void
{
switch (e.keyCode)
{
case 37 :
key_Left = false;
break;
case 38 :
key_Up = false;
break;
case 39 :
key_Right = false;
break;
case 40 :
key_Down = false;
break;
}
}
public function movePlayer():void
{
if (key_Left && !key_Right)
{
player.x -= maxSpeed;
player.rotation = 270;
}
if (key_Right && !key_Left)
{
player.x += maxSpeed;
player.rotation = 90;
}
if (key_Up && !key_Down)
{
player.y -= maxSpeed;
player.rotation = 0;
}
if (key_Down && !key_Up)
{
player.y += maxSpeed;
player.rotation = 180;
}
/*if ( key_Left && key_Up && !key_Right && !key_Down )
{
player.rotation = 315;
}
if ( key_Right && key_Up && !key_Left && !key_Down )
{
player.rotation = 45;
}
if ( key_Left && key_Down && !key_Right && !key_Up )
{
player.rotation = 225;
}
if ( key_Right && key_Down && !key_Left && !key_Up )
{
player.rotation = 135;
}*/
}
public function initPlayer():void
{
player = new Player();
player.x = stage.stageWidth * .5;
player.y = stage.stageHeight * .5;
stage.addChild(player);
}
public function initVariables():void
{
vx = 0;
maxSpeed = 4;
key_Up = false;
key_Down = false;
key_Left = false;
key_Right = false;
maxKey = 3;
keysUp = 0;
doorOpen = false;
wallCollide = false;
bulletTime = 0;
bulletLimit = 12;
bulletShoot = true ;
}
public function collisionDetection():void
{
for (var i:int=0; i < invArray.length; i++)
{
key = invArray[i];
if (player.hitTestObject(key))
{
stage.removeChild(key);
invArray.splice(i, 1);
keysUp++;
//trace(keysUp);
i--;
keyCount.text = String(keysUp);
break;
}
}
if (player.hitTestPoint(door.x,door.y + 25,true) && (keysUp > 0) && ! doorOpen)
{
door.gotoAndStop(2);
keysUp--;
invArray.pop();
trace(keysUp);
keyCount.text = String(keysUp);
doorOpen = true;
}
if (player.hitTestObject(door) && (keysUp == 0) && ! doorOpen)
{
wallCollide = true;
}
if (player.hitTestObject(wall1))
{
wallCollide = true;
}
if (player.hitTestObject(wall2))
{
wallCollide = true;
}
if (wallCollide == true)
{
player.y += 4;
wallCollide = false;
}
}
public function initInventory():void
{
inventory = new Inventory();
inventory.x = stage.stageWidth * .15;
inventory.y = stage.stageHeight * .90;
stage.addChild(inventory);
keyCount = new TextField();
stage.addChild(keyCount);
keyCount.x = inventory.x - 8;
keyCount.y = inventory.y + 3;
keyCount.text = String(keysUp);
//keyCount.border = true;
keyCount.width = 20;
keyCount.height = 20;
}
public function initItems():void
{
while (invArray.length < maxKey)
{
key = new _Key ;
key.x = Math.random() * 550;
key.y = Math.random() * 300;
stage.addChild(key);
invArray.push(key);
}
door = new Door();
door.x = 250;
door.y = 25;
wall1 = new Wall();
stage.addChild(wall1);
wall1.x = door.x - 175;
wall1.y = door.y;
wall2 = new Wall();
stage.addChild(wall2);
wall2.x = door.x + 175;
wall2.y = door.y;
stage.addChild(door);
}
public function bullet():void
{
if (bulletTime < bulletLimit)
{
bulletTime++;
} else
{
bulletShoot = true;
bulletTime = 0;
}
}
}
}
Bullet Class
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip {
public var _root:Object;
public var speed:int = 10;
public var bulletRotation:int;
public function Bullet(pRotation:int) {
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, eFrame);
bulletRotation = pRotation;
}
private function beginClass(e:Event):void
{
_root = MovieClip(root);
}
private function eFrame(e:Event):void
{
if (bulletRotation == 0)
{
this.y -= speed;
}
else if (bulletRotation == 90)
{
this.x += speed;
}
else if(bulletRotation == 270)
{
this.x -= speed;
}
else if(bulletRotation == 180)
{
this.y += speed;
}
if(this.y < -1 * this.height)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
if(this.x < -1 * this.width)
{
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.removeChild(this);
}
}
}
}

In Bullet class, change 270 to -90, at line 38:
else if(bulletRotation == -90)
{
this.x -= speed;
}

Related

How to set only one object to spawn with a timer?

I am currently a beginner trying to learn programming with as3 so bear with me. I have this code so far and my game repeatedly spawns the Food2 (golden apple) but it does not stop. Here is my code so far:
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class Main extends MovieClip{
const speed:int = 10;
var score:int;
var vx:int;
var vy:int;
var gFood:Food;
var gFood2:Food2;
var head:SnakePart;
var SnakeDirection:String;
var snake:Array;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var myTimer:Timer = new Timer(10000,1);
public function Main(){
init();
gotoAndStop(1);
}
function init():void {
vx = 1; vy = 0;
score = 0;
snake = new Array();
SnakeDirection = "";
addFood();
myTimer.start();
head = new SnakePart();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
start1.addEventListener(MouseEvent.CLICK, startgame);
help1.addEventListener(MouseEvent.CLICK, helpplayer);
stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
}
private function startgame(event:MouseEvent):void {
gotoAndPlay(3);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
stop();
}
private function helpplayer(event:MouseEvent):void {
gotoAndPlay(2);
stop();
}
function addFood():void {
gFood = new Food();
gFood.x = 50 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
function addFood2():void {
gFood2 = new Food2();
gFood2.x = 70 + Math.random()*(stage.stageWidth-100);
gFood2.y = 70 + Math.random()*(stage.stageHeight-100);
addChild(gFood2);
}
function reset():void {
gotoAndStop(1);
score = 0;
removeChild(gFood);
removeChild(gFood2);
myTimer.stop();
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
SnakeDirection = "left";
}else if (event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "right";
}else if (event.keyCode == Keyboard.UP) {
SnakeDirection = "up";
}else if (event.keyCode == Keyboard.DOWN) {
SnakeDirection = "down";
}
}
function onKeyUp(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.LEFT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.RIGHT) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.UP ) {
SnakeDirection = "";
}else if(event.keyCode == Keyboard.DOWN){
SnakeDirection = "";
}
}
function onEnterFrame(event:Event):void {
Timerfood();
txtScore.text = "Score:" + String(score);
if(SnakeDirection == "left" && vx != 1) {
vx = -1;
vy = 0;
}
else if(SnakeDirection == "right" && vx != -1) {
vx = 1;
vy = 0;
}
else if(SnakeDirection == "up" && vy != 1) {
vx = 0;
vy = -1;
}
else if(SnakeDirection == "down" && vy != -1) {
vx = 0;
vy = 1;
}
if(head.x - head.width/2 <= 0){
score = 0;
reset();
}
if(head.x + head.width/2 >= stage.stageWidth){
score = 0;
reset();
}
if(head.y - head.height/2 <= 0){
score = 0;
reset();
}
if(head.y + head.height/2 >= stage.stageHeight){
score = 0;
reset();
}
for(var i = snake.length-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
head.x += vx*speed;
head.y += vy*speed;
for(var i = snake.length-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
if(head.hitTestObject(gFood)){
score += 1;
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
score += 2;
removeChild(gFood2);
bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
function Keyboard_a(event:KeyboardEvent):void {
if (event.keyCode == 82) {
resetgame();
}
}
function resetgame():void {
score = 0;
if (contains(head))
removeChild(head);
init();
}
}
function Timerfood():void {
var myTimer:Timer = new Timer(10000,1);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener(e:TimerEvent):void{
trace("Timer is Triggered");
addFood2();
}
myTimer.start();
}
}
}
It's hard to understand what specific logic you want to implement, but it looks like you need to create an enemy only once. And it looks like the problem is: you call the Timerfood method in the onEnterFrame listeners, which itself is called many times per second according to the framerate of your app (e.g. 30 times per second).
I would suggest you to remove the call of Timerfood from the onEnterFrame method, and put it in the end of the init method.
Well, my English is not very good, but I try tell the possible reason,
the method Timerfood() is called on method onEnterFrame(), that initialize myTimer for each frame, so may be the solution is, remove this line into TimerFood() method:
var myTimer:Timer = new Timer(10000,1);
and call TimerFood() only in startgame() method.
I hope you can understand me.

How do I call methods and properties from parent classes?

I'm new here (and also relatively new with AS3 as well), so bear with me.
I've only discovered OOP 2 weeks ago, and before then, I knew only the most rudimentary knowledge of AS3. So I did make a lot of improvement, but one thing's been bugging me.
I can never seem to call functions and methods from parent classes. Even with setters and getters, the child class always gives me an output error. It looks something like this.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Axiom/clicked()
This is an AS3 project that I'm working on right now that is giving me this problem.
Here's some basic background of the project.
I have the main class, called Main, and some other classes, called Axiom and Textbox. Main creates Axiom into a movieclip (background) that's already present on the stage. Axiom creates Textbox when clicked. Axiom calls a method called mouseClick from Main (plays a sound), and Textbox calls some properties from Axiom (text for the textbox).
I have attempted to use
MovieClip(this.parent).mouseClick();
and declaring a new variable in the child class, like this.
private var main:Main;
...
main.mouseClick();
And this leads me to question - what am I doing wrong, and how should I do it properly?
Here are the classes for reference.
Main.as
package {
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Mouse;
import flash.events.MouseEvent;
public class Main extends MovieClip {
// sound
private var music:Music = new Music();
private var clickSound:Click = new Click();
// instructions
private var instructions:Instructions = new Instructions();
// mouse
private var cursor:Cursor = new Cursor();
// player
private var player:Player = new Player();
private var animationState:String = "standing";
private var directionState:String = "right";
// Axiom
private var axiom:Axiom = new Axiom();
// movement
private var rightPressed:Boolean = false;
private var leftPressed:Boolean = false;
private var upPressed:Boolean = false;
private var downPressed:Boolean = false;
private var xMovement:Number = 0;
private var yMovement:Number = 0;
private var speed:Number = 22;
private var friction:Number = 0.9;
private var rDoubleTapCounter:int = 0;
private var lDoubleTapCounter:int = 0;
private var dDoubleTapCounter:int = 0;
private var uDoubleTapCounter:int = 0;
private var doubleTapCounterMax:int = 5;
private var running:Boolean = false;
public function Main() {
// constructor code
// mouse
stage.addChild(cursor);
cursor.mouseEnabled = false;
Mouse.hide();
// instructions
instructions.x = 640;
instructions.y = 120;
stage.addChild(instructions);
// add player
player.x = 642;
player.y = 448.95;
player.gotoAndStop(directionState);
player.right.gotoAndStop(animationState);
addChild(player);
// add Axiom
axiom.x = 300;
axiom.y = -150;
back.addChild(axiom);
// keyboard events
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
// music
music.play(0, int.MAX_VALUE);
// loop
stage.addEventListener(Event.ENTER_FRAME, loop);
}
private function loop(e:Event):void {
// set mouse
cursor.x = stage.mouseX;
cursor.y = stage.mouseY;
// set Movement to speed
if (rightPressed) {
if (upPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * -2;
} else {
xMovement = speed;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (rDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * 2;
yMovement = speed * 2;
} else {
xMovement = speed;
yMovement = speed;
}
} else if (running || rDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * 2;
} else {
xMovement = speed;
}
} else if (leftPressed) {
if (upPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && uDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * -2;
} else {
xMovement = speed * -1;
yMovement = speed * -1;
}
} else if (downPressed) {
if (running || (lDoubleTapCounter <= doubleTapCounterMax && dDoubleTapCounter <= doubleTapCounterMax)) {
xMovement = speed * -2;
yMovement = speed * 2;
} else {
xMovement = speed * -1;
yMovement = speed;
}
} else if (running || lDoubleTapCounter <= doubleTapCounterMax) {
xMovement = speed * -2;
} else {
xMovement = speed * -1;
}
} else if (downPressed) {
if (dDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
} else if (upPressed) {
if (uDoubleTapCounter <= doubleTapCounterMax || running) {
yMovement = speed * -2;
} else {
yMovement = speed * -1;
}
}
// double tap counter
if (rightPressed == false) {
rDoubleTapCounter++;
}
if (leftPressed == false) {
lDoubleTapCounter++;
}
if (downPressed == false) {
dDoubleTapCounter++;
}
if (upPressed == false) {
uDoubleTapCounter++;
}
// change labels
if (player.currentLabel != animationState) {
player.right.gotoAndStop(animationState);
}
// friction
xMovement *= friction;
yMovement *= friction;
// animationState and stop
if (Math.abs(xMovement) > 1) {
if (Math.abs(xMovement) > 22) {
animationState = "running";
running = true;
} else {
animationState = "trotting";
running = false;
}
} else {
animationState = "standing";
xMovement = 0;
}
// right or left facing
if (xMovement > 0) {
player.scaleX = 1;
} else if (xMovement < 0) {
player.scaleX = -1;
}
//movement
if (back.x >= back.width / 2 - 50) {
if (player.x >= 642 && xMovement > 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x <= player.width / 2 && xMovement < 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else if (back.x <= 1280 - back.width / 2 + 50) {
if (player.x <= 642 - 30 && xMovement < 0) {
player.x = 642;
back.x -= xMovement;
} else {
if (player.x >= 1280 + 30 - player.width / 2 && xMovement > 0) {
xMovement = 0;
} else {
player.x += xMovement;
}
}
} else {
back.x -= xMovement;
}
}
private function keyPressed(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = true;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = true;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = true;
} else if (e.keyCode == Keyboard.UP) {
upPressed = true;
}
}
private function keyReleased(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.RIGHT) {
rightPressed = false;
rDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.LEFT) {
leftPressed = false;
lDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.DOWN) {
downPressed = false;
dDoubleTapCounter = 0;
} else if (e.keyCode == Keyboard.UP) {
upPressed = false;
uDoubleTapCounter = 0;
}
}
public function mouseClick():void {
clickSound.play();
}
}
}
Axiom.as
package {
import flash.events.MouseEvent;
import flash.events.EventDispatcher;
import flash.display.MovieClip;
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main;
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
main.mouseClick();
stage.addChild(speechBox);
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
Textbox.as
package {
import flash.events.MouseEvent;
import flash.display.MovieClip;
import com.greensock.TweenLite;
public class Textbox extends MovieClip{
private var axiom:Axiom;
private var main:Main;
public function Textbox() {
// constructor code
this.x = 40;
this.y = 360;
this.textBox.text = axiom.words;
TweenLite.from(this, 0.3, {x: "10", alpha: 0});
this.addEventListener(MouseEvent.CLICK, nextPage);
}
private function nextPage(e:MouseEvent):void{
main.mouseClick();
TweenLite.to(this, 0.3, {x: "-10", alpha: 0});
MovieClip(this.parent).removeThis();
}
}
}
Instead of trying to call functions of the parent (rarely a good idea), use Events instead.
In your Axiom Class:
package {
...import statements
public class Axiom extends MovieClip {
private var speechBox:Textbox = new Textbox();
private var speech:String = "Something came out of that pop.";
private var main:Main; //this shouldn't be here, ideally, Axiom knows NOTHING about the main class.
public function Axiom() {
// constructor code
this.addEventListener(MouseEvent.CLICK, onClickStage);
this.addEventListener(MouseEvent.CLICK, clicked);
}
private function onClickStage(e:MouseEvent):void {
trace(e.target,e.target.name);
}
private function clicked(e:MouseEvent):void {
//main.mouseClick(); // unneccesary
dispatchEvent(e); //the event you caught by performing a click will be dispatched again, so that the parent can react to it
stage.addChild(speechBox); //Axiom might not have access to the stage, addChild would suffice
this.removeEventListener(MouseEvent.CLICK, clicked);
}
public function get words():String {
return speech;
}
public function removeThis():void {
this.addEventListener(MouseEvent.CLICK, clicked);
removeChild(speechBox);
}
}
}
and in your Main Class
axiom.addEventListener(MouseEvent.CLICK, onAximClicked);
private function onAxiomClicked(e:MouseEvent):void{
//now you can use the parents (in this case an Object of the Main class) functions
mouseClick();
}

as3 flashdevelop freezes after build

Currently my game seems to work fine, the only problem it has is the builder does not respond 8 out of 10 times. The question is why does it stop working and how can I solve it.
Here is my code.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* ...
* #author BLANK
*/
public class Main extends Sprite
{
public var start:StartScherm = new StartScherm;
public var button:Startbutton = new Startbutton;
public var balletje:Ball = new Ball;
public var player1:Player = new Player;
public var player2:Player2 = new Player2;
public var player3:Player3 = new Player3;
public var player4:Player4 = new Player4;
public var background:Background = new Background;
public var kader:Kader = new Kader;
public var scoreboard:Monkeys = new Monkeys;
public var leven1:Life = new Life;
public var leven2:Life2 = new Life2;
public var leven3:Life3 = new Life3;
public var leven4:Life4 = new Life4;
public var wall1:Walls = new Walls;
public var wall2:Wall2 = new Wall2;
public var wall3:Wall3 = new Wall3;
public var wall4:Wall4 = new Wall4;
public static var KEY_LEFT1:Boolean = false;
public static var KEY_LEFT2:Boolean = false;
public static var KEY_LEFT3:Boolean = false;
public static var KEY_LEFT4:Boolean = false;
public static var KEY_RIGHT1:Boolean = false;
public static var KEY_RIGHT2:Boolean = false;
public static var KEY_RIGHT3:Boolean = false;
public static var KEY_RIGHT4:Boolean = false;
public var GAME:Boolean = false;
public var RESET:Boolean = false;
public var ballSpeedX:int = -3;
public var ballSpeedY:int = -2;
public var LIFE1:Number = 10;
public var LIFE2:Number = 10;
public var LIFE3:Number = 10;
public var LIFE4:Number = 10;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
stage.addEventListener(Event.ENTER_FRAME, loop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
addChild(start);
addChild(button);
}
private function gameStart():void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
if (stage) world();
else addEventListener(Event.ADDED_TO_STAGE, world);
}
private function gameReset():void
{
removeEventListener(Event.ADDED_TO_STAGE, world);
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function world(e:Event = null):void
{
addChild(background);
addChild(kader);
addChild(player1);
addChild(player2);
addChild(player3);
addChild(player4);
addChild(scoreboard);
addChild(leven1);
addChild(leven2);
addChild(leven3);
addChild(leven4);
addChild(balletje);
}
private function loop(e:Event):void
{
//balletje.update();
if (GAME == true)
{
removeEventListener(Event.ADDED_TO_STAGE, init);
removeChild(start);
removeChild(button);
gameStart();
}
if (RESET == true)
{
removeEventListener(Event.ADDED_TO_STAGE, world);
removeChild(background);
removeChild(kader);
removeChild(player1);
removeChild(player2);
removeChild(player3);
removeChild(player4);
removeChild(scoreboard);
removeChild(leven1);
removeChild(leven2);
removeChild(leven3);
removeChild(leven4);
removeChild(balletje);
removeChild(wall1);
removeChild(wall2);
removeChild(wall3);
removeChild(wall4);
LIFE1 = 3;
LIFE2 = 3;
LIFE3 = 3;
LIFE4 = 3;
gameReset();
}
if (LIFE1 == 0)
{
removeChild(leven1);
addChild(wall1);
}
if (LIFE1 == 1)
{
leven1.width = 10;
leven1.height = 10;
}
if (LIFE1 == 2)
{
leven1.width = 30;
leven1.height = 30;
}
if (LIFE2 == 0)
{
removeChild(leven2);
addChild(wall2);
}
if (LIFE2 == 1)
{
leven2.width = 10;
leven2.height = 10;
}
if (LIFE2 == 2)
{
leven2.width = 30;
leven2.height = 30;
}
if (LIFE3 == 0)
{
removeChild(leven3);
addChild(wall3);
}
if (LIFE3 == 1)
{
leven3.width = 10;
leven3.height = 10;
}
if (LIFE3 == 2)
{
leven3.width = 30;
leven3.height = 30;
}
if (LIFE4 == 0)
{
removeChild(leven4);
addChild(wall4);
}
if (LIFE4 == 1)
{
leven4.width = 10;
leven4.height = 10;
}
if (LIFE4 == 2)
{
leven4.width = 30;
leven4.height = 30;
}
balletje.x += ballSpeedX;
balletje.y += ballSpeedY;
if(balletje.x <= -350-balletje.width/2){ //check if the x position of the left side of the ball is less than or equal to the left side of the screen, which would be 0
balletje.x = -350-balletje.width/2; //then set the ball's x position to that point, in case it already moved off the screen
ballSpeedX *= -1; //and multiply the ball's x speed by -1, which will make it move right instead of left
LIFE2 -= 1;
} else if(balletje.x >= 350-balletje.width/2){ //check to see the right side of the ball is touching the right boundary, which would be 550
balletje.x = 350-balletje.width/2; //reposition it, just in case
ballSpeedX *= -1; //multiply the x speed by -1 (now moving left, not right)
LIFE4 -= 1;
}
//now we do the same with the top and bottom of the screen
if(balletje.y <= -350-balletje.height/2){ //if the y position of the top of the ball is less than or equal to the top of the screen
balletje.y = -350-balletje.height/2; //like we did before, set it to that y position...
ballSpeedY *= -1; //...and reverse its y speed so that it is now going down instead of up
LIFE3 -= 1;
} else if(balletje.y >= 350-balletje.height/2){ //if the bottom of the ball is lower than the bottom of the screen
balletje.y = 350-balletje.height/2; //reposition it
ballSpeedY *= -1; //and reverse its y speed so that it is moving up now
LIFE1 -= 1;
}
if( player1.hitTestObject(balletje) == true ){
if(ballSpeedX < 0){
ballSpeedY *= -1;
ballSpeedX = calculateBallAngle2(player1.x, balletje.x);
}
if(ballSpeedX > 0){
ballSpeedY *= 1;
ballSpeedX = calculateBallAngle2(player1.x, balletje.x);
}
} else if(player2.hitTestObject(balletje) == true ){
if(ballSpeedX > 0){
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(player2.y, balletje.y);
}
if(ballSpeedX < 0){
ballSpeedX *= 1;
ballSpeedY = calculateBallAngle(player2.y, balletje.y);
}
} else if(player3.hitTestObject(balletje) == true ){
if(ballSpeedX > 0){
ballSpeedY *= -1;
ballSpeedX = calculateBallAngle2(player3.x, balletje.x);
}
if(ballSpeedX < 0){
ballSpeedY *= 1;
ballSpeedX = calculateBallAngle2(player3.x, balletje.x);
}
}
else if(player4.hitTestObject(balletje) == true ){
if(ballSpeedX > 0){
ballSpeedX *= -1;
ballSpeedY = calculateBallAngle(player4.y, balletje.y);
}
if(ballSpeedX < 0){
ballSpeedX *= 1;
ballSpeedY = calculateBallAngle(player4.y, balletje.y);
}
}
if (KEY_LEFT1 == true)
{
player1.x -= 10;
}
if (KEY_LEFT2 == true)
{
player1.x += 10;
}
if (KEY_LEFT3 == true)
{
player3.x -= 10;
}
if (KEY_LEFT4 == true)
{
player3.x += 10;
}
if (KEY_RIGHT1 == true)
{
player2.y += 10;
}
if (KEY_RIGHT2 == true)
{
player2.y -= 10;
}
if (KEY_RIGHT3 == true)
{
player4.y += 10;
}
if (KEY_RIGHT4 == true)
{
player4.y -= 10;
}
}
private function keyDown(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
KEY_LEFT1 = true;
}
if (e.keyCode == 39)
{
KEY_LEFT2 = true;
}
if (e.keyCode == 67)
{
KEY_LEFT3 = true;
}
if (e.keyCode == 86)
{
KEY_LEFT4 = true;
}
if (e.keyCode == 65)
{
KEY_RIGHT1 = true;
}
if (e.keyCode == 81)
{
KEY_RIGHT2 = true;
}
if (e.keyCode == 102)
{
KEY_RIGHT3 = true;
}
if (e.keyCode == 105)
{
KEY_RIGHT4 = true;
}
if (e.keyCode == 13)
{
GAME = true;
}
if (e.keyCode == 8)
{
RESET = true;
}
}
private function keyUp(e:KeyboardEvent):void
{
if (e.keyCode == 37)
{
KEY_LEFT1 = false;
}
if (e.keyCode == 39)
{
KEY_LEFT2 = false;
}
if (e.keyCode == 67)
{
KEY_LEFT3 = false;
}
if (e.keyCode == 86)
{
KEY_LEFT4 = false;
}
if (e.keyCode == 65)
{
KEY_RIGHT1 = false;
}
if (e.keyCode == 81)
{
KEY_RIGHT2 = false;
}
if (e.keyCode == 102)
{
KEY_RIGHT3 = false;
}
if (e.keyCode == 105)
{
KEY_RIGHT4 = false;
}
if (e.keyCode == 13)
{
GAME = false;
}
if (e.keyCode == 8)
{
RESET = false;
}
}
public function calculateBallAngle(paddleY:Number, ballY:Number):Number
{
var ySpeed:Number = 1 * ( (ballY-paddleY) / 40 );
return ySpeed;
}
public function calculateBallAngle2(paddleX:Number, ballX:Number):Number
{
var xSpeed:Number = 1 * ( (ballX-paddleX) / 40 );
return xSpeed;
}
}
}
Thanks in advance.

Error #1034: Type Coercion failed: cannot convert flash.display::Stage#27dfe089 to flash.display.MovieClip

here it is the error >> TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage#261b4089 to flash.display.MovieClip.
at com.ply::Heli/fireBullet()
at com.ply::Heli/myOnPress()
this is Heli's Class :
package com.ply
{
import flash.display.MovieClip;
import flash.display.*;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import com.peluru.Bullet;
public class Heli extends MovieClip
{
var shotCooldown:int;
const MAX_COOLDOWN = 10;
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
public function Heli()
{
shotCooldown = MAX_COOLDOWN;
bullets = new Array();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, RunHeli);
}
private function RunHeli(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
public function update(e:Event){
shotCooldown-- ;
}
/**
* Keyboard Handlers
*/
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
yAcceleration = 1;
}
else if (event.keyCode == 32)
{
fireBullet();
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
yAcceleration = 0;
}
}
public function fireBullet() {
if (shotCooldown <=0 )
{
shotCooldown=MAX_COOLDOWN;
var b = new Bullet();
var b2= new Bullet();
b.x = this.x +20;
b.y = this.y ;
b2.x= this.x -20;
b2.y= this.y ;
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
trace(bullets.length);
parent.addChild(b);
parent.addChild(b2);
}
}
}
}
and this is the Main Class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
private var nextPlane:Timer;
public var enemies:Array;
public var bullets:Array;
public function Main()
{
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
enemies = new Array();
bullets = ne Array();
setNextPlane();
gameState = STATE_START_PLAYER;
gameLoop();
//stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
stage.addEventListener(Event.ENTER_FRAME, back);
stage.addEventListener(Event.ENTER_FRAME,checkForHits);
}
public function setNextPlane() {
nextPlane = new Timer(1000+Math.random()*1000,1);
nextPlane.addEventListener(TimerEvent.TIMER_COMPLETE,newPlane);
nextPlane.start();
}
public function newPlane(event:TimerEvent) {
// random side, speed and altitude
// create plane
var enemy:Airplane2 = new Airplane2();
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
enemies.push(enemy);
// set time for next plane
setNextPlane();
}
public function removePlane(plane:Airplane2) {
for(var i in enemies) {
if (enemies[i] == plane) {
enemies.splice(i,1);
break;
}
}
}
// take a bullet from the array
public function removeBullet(bullet:Bullet) {
for(var i in bullets) {
if (bullets[i] == bullet) {
bullets.splice(i,1);
break;
}
}
}
public function checkForHits(event:Event) {
for(var bulletNum:int=bullets.length-1;bulletNum>=0;bulletNum--){
for (var airplaneNum:int=enemies.length-1;airplaneNum>=0;airplaneNum--) {
if (bullets[bulletNum].hitTestObject(enemies[airplaneNum])) {
enemies[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
trace("kena");
//shotsHit++;
//showGameScore();
break;
}
}
}
//if ((shotsLeft == 0) && (bullets.length == 0)) {
// endGame();
//}
}
public function back( evt:Event ):void
{ // Backgroud Land
if (Dessert2.y >= 0 && Dessert.y >= 720)
{
Dessert.y = Dessert2.y - 1240 ;
}
else if (Dessert.y >= 0 && Dessert2.y >= 720)
{
Dessert2.y = Dessert.y - 1240 ;
}
else
{
Dessert.y = Dessert.y +5 ;
Dessert2.y = Dessert2.y +5 ;
}
// Background Clouds
if (Clouds2.y >= 0 && Clouds.y >= 720)
{
Clouds.y = Clouds2.y - 2480 ;
}
else if (Clouds.y >= 0 && Clouds2.y >= 720)
{
Clouds2.y = Clouds.y - 2480 ;
}
else
{
Clouds.y = Clouds.y +10 ;
Clouds2.y = Clouds2.y +10 ;
}
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
gameLoop();
//txtScore.text = 'Score: '+score;
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
}
}
You have added your player in Main into stage instead of this - why, by the way? So, there are two methods of fixing this: First, change line where you add player to display list, and second, remove direct coercion from Heli.fireBullet() function. I'd say use the first one.
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add Player to display list
this.addChild(player); // <-- this, not stage
gameState = STATE_PLAY_GAME;
}
Change
MovieClip(parent).bullets.push(b);
MovieClip(parent).bullets.push(b2);
to
MovieClip(root).bullets.push(b);
MovieClip(root).bullets.push(b2);

TypeError: Error #1009: Cannot access a property or method of a null reference

I am creating a platformer game. However, I have encountered an error after creating a collision boundary on platform to make the player jump on the platform without dropping.
I have create a rectangle box and I export it as platForm
Here's the output of the error:
The error keep repeating itself over and over again....
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Boy/BoyMove()
Main class:
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class:
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 15;
//whether or not the main guy is jumping
//var mainJumping:Boolean = false;
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var gravity:Number = 10;
var theGround:ground = new ground();
//var theCharacter:MovieClip;
public var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, BoyMove);
}
public function BoyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (MovieClip(this).y > 500)
{
mainJumping = false;
MovieClip(this).y = 500;
}
this.y = currentY;
}
}
}
Platformer class: This is the class I want to set the boundary for the rectangle (platForm)
package
{
import flash.events.*;
import flash.display.MovieClip;
public class platForm extends MovieClip
{
var level:Array = new Array();
var classBoys:Boy = new Boy();
var speedx:int = MovieClip(classBoys).currentX;
public function platForm()
{
for (var i = 0; i < numChildren; i++)
{
if (getChildAt(i) is platForm)
{
level.push(getChildAt(i).getRect(this));
}
}
for (i = 0; i < level.length; i++)
{
if (MovieClip(classBoys).getRect(this).intersects(level[i]))
{
if (speedx > 0)
{
MovieClip(classBoys).x = level[i].left - MovieClip(classBoys).width/2;
}
if (speedx < 0)
{
MovieClip(classBoys).x = level[i].right - MovieClip(classBoys).width/2;
}
}
}
}
}
}
It's a little difficult to see exactly what is happening without being able to run your code, but the error is saying that something within your BoyMove() method is trying to reference a property (or method) of something that is null. Having looked at the BoyMove() method, I can see that there isn't a lot there that could cause this problem. The other two candidates would be
MovieClip(parent)
or
MovieClip(this)
You are attempting to access properties of both of those MovieClips. One of them must not be initialized as you expect. I suggest you do some basic debugging on that method by commenting out the lines with MovieClip(parent) and see if you still get the error. Then try the same with the line with MovieClip(this). That should be able enough to isolate the issue.