Signals Keyboard Movement AS3 - actionscript-3

I'm trying to get my keyboard movement to work using signals and a Hero class. So far I can get the signal to dispatch but I can't get it to take the keyboard input. Should I be using signals for movement at all or should I just call the function from the Hero class.
This is the code for Hero:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import org.osflash.signals.Signal;
import flash.events.Event;
import com.natejc.input.KeyboardManager;
import com.natejc.input.KeyCode;
/**
* ...
* #author Kevin Raskell
*/
public class Hero extends MovieClip
{
public var defeatedSignal :Signal = new Signal();
public var _nHeroMovement :Number = 5;
public var moveSignal :Signal;
public function Hero()
{
super();
this.mouseChildren = false;
this.mouseEnabled = false;
this.addEventListener(Event.ENTER_FRAME, heroMovement);
moveSignal = new Signal();
}
public function heroDefeated()
{
trace("You have died");
}
public function heroMovement($e:Event):void
{
moveSignal.dispatch();
if (this)
{
if (KeyboardManager.instance.isKeyDown(KeyCode.DOWN))
{
if (this.y + this.height > this.stage.stageHeight || this.y - this.height <= 0)
{
this.y += -15;
this.gotoAndPlay("Idle");
return;
}
this.y += _nHeroMovement;
this.gotoAndPlay("Down");
}
else if (KeyboardManager.instance.isKeyDown(KeyCode.UP))
{
if (this.y + this.height > this.stage.stageHeight || this.y - this.height <= 0)
{
this.y += 15;
this.gotoAndPlay("Idle");
return;
}
this.y -= _nHeroMovement;
this.gotoAndPlay("Up");
}
if (KeyboardManager.instance.isKeyDown(KeyCode.LEFT))
{
if (this.x + this.width > this.stage.stageWidth || this.x - this.width <= 0)
{
this.x += 15;
this.gotoAndPlay("Idle");
return;
}
this.x -= _nHeroMovement;
this.gotoAndPlay("Left");
}
else if (KeyboardManager.instance.isKeyDown(KeyCode.RIGHT))
{
if (this.x + this.width > this.stage.stageWidth || this.x - this.width <= 0)
{
this.x += -15;
this.gotoAndPlay("Idle");
return;
}
this.x += _nHeroMovement;
this.gotoAndPlay("Right");
}
}//end if
}//end heroMovement
}//end Hero
}//end package
This is in the main function:
this.mcHero.moveSignal.add(moveHero);
}
private function moveHero():void
{
trace("Testing" + count);
count++;
}
The counting was for testing purposes for myself to see what was happening.

Related

Access of possibly undefined property alpha through a reference with static type Class

I'm not sure how to go about setting the transparency when the character's health goes down.
Error is on line 38
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
public class Character extends MovieClip
{
var velocity:Number;
var shootLimiter:Number;
var health:Number;
var maxHealth:Number;
public function Character()
{
velocity = 10;
shootLimiter = 0;
health = 100;
maxHealth = 100;
addEventListener("enterFrame", move);
x = 300
y = 150
}
function takeDamage(d)
{
health -= d;
if(health <= 0)
{
health = 0;
kill();
}
Game.healthMeter.bar.scaleX = health/maxHealth;
Character.alpha = health/100;
}
function kill()
{
var blood = new Blood();
stage.addChild(blood);
blood.x = this.x;
blood.y = this.y;
removeEventListener("enterFrame",move);
this.visible = false;
Game.gameOver();
}
function move(e:Event)
{
shootLimiter += 5;
if(Key.isDown(Keyboard.RIGHT))
{
if(this.x <= 560)
{
this.x = this.x + velocity;
}
}
if(Key.isDown(Keyboard.LEFT))
{
if(this.x >= 40)
{
this.x = this.x - velocity;
}
}
if(Key.isDown(Keyboard.UP))
{
if(this.y > 20)
{
this.y = this.y - velocity;
}
}
if(Key.isDown(Keyboard.DOWN))
{
if(this.y < 280)
{
this.y = this.y + velocity;
}
}
if(Key.isDown(Keyboard.SPACE) && shootLimiter > 8)
{
shootLimiter = 0;
var b = new Needles();
stage.addChild(b);
b.x = this.x+65;
b.y = this.y+45;
}
}
}
}
Character has no static property called alpha. You are referring to the instance of the class and therefore it should be this.alpha = health/100; instead of Character.alpha = health/100;

How to implement enemy behaviour based on type?

I am building a game which create three types of enemy.Amount them only type 3 can fire others cannt.This is my enemy class
package
{
import flash.display.MovieClip;
import flash.utils.getTimer;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.Point;
public class Enemy extends MovieClip
{
private var lastTime:int;
var hitCounter:Number = 1;
public var eType:Number = 0;
private var startYpos:Number = 0;
var nextFire:Timer;
var enemyType:Number;
public var bullets:Array = new Array ;
var speedY:Number = 50;
var enemySpeed:Number = 50;
var firstPos:Number = 0;
var fireCounter:Number = 0;
var firePause:Number = 10;
public function Enemy(xPos,yPos:Number,t:Number)
{
// constructor code
this.x = xPos;
firstPos = this.y = yPos;
this.enemyType = t;
lastTime = getTimer();
this.gotoAndStop(t);
addEventListener(Event.ENTER_FRAME,moveEnemy);
}
public function moveEnemy(event:Event)
{
// get time passed
var timePassed:int = getTimer() - lastTime;
lastTime += timePassed;
// move bullet
if (this.y + this.height / 2 > firstPos + 100 && speedY > 0)
{
speedY *= -1;
}
if (this.y - this.height / 2 < firstPos && speedY < 0)
{
speedY *= -1;
}
this.x -= enemySpeed * timePassed / 1000;
this.y += speedY * timePassed / 1000;
// bullet past top of screen
if (this.x - this.width / 2 < 0)
{
deleteEnemy();
}
if (this.enemyType == 3)
{
canFire();
}
}
public function canFire()
{
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
public function deleteEnemy()
{
if (this.currentFrame == 2)
{
this.gotoAndStop(4);
}
else
{
//trace(MovieClip(parent).enemyKilled[this.enemyType-1]);
MovieClip(parent).enemyKilled[this.enemyType - 1]++;
MovieClip(parent).removeEnemy(this);
parent.removeChild(this);
removeEventListener(Event.ENTER_FRAME,moveEnemy);
}
}
}
}
Now once a enemy type 3 start firing then every enemy start firing.i want just only enemy type 3 can fire not other enemy.How i do it?
Thanks in advance
Addition :
public function createEnemyBullet()
{
var bullet:Bullet = new Bullet(enemy.x - 10,enemy.y,500,-1);
bullets.push(bullet);
addChild(bullet);
//setEnemyBullet();
}
Then why don't you try something like this. `
public function canFire()
{
if(enemyType == 3){
return;
}
if ((fireCounter > firePause))
{
MovieClip(parent).createEnemyBullet();
trace((('Enemy Type : ' + enemyType) + ' and firing'));
fireCounter = 0;
}
else
{
fireCounter++;
}
}
`

As3: removing programmatically added child on hit test gives error #1009

I have tried removing programatically added movieclips when they collide with a certain object. When they do, they vanish. But after they have vanished, I get a #1009 error.
The error points at line 95, which is
if (this.x > stage.stageWidth + 2 - (stage.stageWidth - (this.width /2)) && this.x < stage.stageWidth - (this.width /2))"
And sometimes at 59, which is
if (this.x >= stage.stageWidth - 20)"
Why does it keep trying to run line 95 (and sometimes) 59? I removed the eventlistener.
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.utils.*;
public class Worker extends MovieClip
{
private var _root:MovieClip;
private var actualRange:Number;
private var reachedGoal:Boolean = false;
private var b:uint;
private var destination:Number;
private var goRight:Boolean = true;
private var goNowhere:Boolean = true;
private var yDir:Number;
private var yNumber:Number;
public function Worker()
{
addEventListener(Event.ADDED, beginClass);
addEventListener(Event.ENTER_FRAME, loop);
//defining _root as the document root
actualRange =(Math.floor(Math.random() * (520 - 80 + 1)) + 80);
b = setInterval(startInc, 3000);
}
private function beginClass(event:Event):void{
//defining _root as the document root
_root = MovieClip(root);
}
private function loop(event:Event):void
{
if (this.hitTestObject(_root.killGun))
{
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
}
}
if (reachedGoal == true)
{
if (goNowhere == true)
{
gotoAndStop(1);
}
//Boundaries
if (this.x <= 20)
{
goRight = true;
goNowhere = false;
}
if (this.x >= stage.stageWidth - 20)
{
goRight = false;
goNowhere = false;
}
if (this.y >= stage.stageHeight - 20)
{
yDir = 0
}
if (this.y <= 20)
{
yDir = 1
}
}
//Intro walk
if (reachedGoal == false)
{
if (this.x < actualRange)
{
gotoAndStop(4);
this.x += 3
}
if (this.x >= actualRange)
{
reachedGoal = true;
gotoAndStop(1);
}
}
//Main walk
if (this.x > stage.stageWidth + 2 - (stage.stageWidth - (this.width /2)) && this.x < stage.stageWidth - (this.width /2))
{
if (goNowhere == false)
{
if (goRight == true)
{
this.x += 1;
gotoAndStop(2);
//Y value
}
if (goRight == false)
{
if (this.x < stage.stageWidth - this.width /2)
this.x -= 1
gotoAndStop(3);
//Y value
if (yNumber == 1)
{
if(yDir == 0)
{
this.y -= 1;
}
if (yDir == 1)
{
this.y += 1;
}
}
}
}
}
}
//Timer functions
private function completePlay()
{
clearInterval(b);
}
private function startInc()
{
var moveNumber:Number = Math.floor(Math.random() * 20);
if (moveNumber == 1)
{
destination = Math.floor(Math.random() * 50);
yDir = Math.floor(Math.random() * 2);
yNumber = Math.floor(Math.random() * 4);
goRight = true;
goNowhere = false;
}
else if (moveNumber == 2)
{
destination = Math.floor(Math.random() * 50);
yDir = Math.floor(Math.random() * 2);
yNumber = Math.floor(Math.random() * 4);
goRight = false;
goNowhere = false;
gotoAndStop(3);
}
else
{
goNowhere = true;
}
}
//End
}
}
The error is happening because you're removing the eventListener within the eventListener's function and your removing the object from it's parent and still processing data that the object no longer contains or has been nullified. You should add a boolean to tell if the hitTest has occured and then not process any more of the loop. For instance:
private function loop(event:Event):void
{
var objectHit:Boolean = false;
objectHit = this.hitTestObject(_root.killGun);
if(!objectHit) {
if (reachedGoal == true)
{
if (goNowhere == true)
{
gotoAndStop(1);
}
//Boundaries
if (this.x <= 20)
{
goRight = true;
goNowhere = false;
}
if (this.x >= stage.stageWidth - 20)
{
goRight = false;
goNowhere = false;
}
if (this.y >= stage.stageHeight - 20)
{
yDir = 0
}
if (this.y <= 20)
{
yDir = 1
}
}
//Intro walk
if (reachedGoal == false)
{
if (this.x < actualRange)
{
gotoAndStop(4);
this.x += 3
}
if (this.x >= actualRange)
{
reachedGoal = true;
gotoAndStop(1);
}
}
}
if (objetHit)
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
}
}
You should also remove the Event.ADDED listener once the object has been added.
private function beginClass(event:Event):void{
//defining _root as the document root
_root = MovieClip(root);
this.removeEventListener(Event.ADDED, beginClass);
}
Could it be that the rest of the loop is trying to run still?
Try breaking out of the loop after the hit:
if (this.hitTestObject(_root.killGun))
{
removeEventListener(Event.ENTER_FRAME, loop);
_root.removeChild(this);
return;
}

Adobe Flash Game Programming

I'm programming a ball game in Adobe Flash, Javascript 3 and I getting a error at line 113( the last line ) that says:
1087: Syntax error: extra characters found after end of program.
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class DocumentMain extends MovieClip
{
public const GRAVITY:Number = 2;
public const BOUNCE_FACTOR:Number = 0.8;
public var _bounces:TextField;
public var _highscore:TextField;
public var _ball:Ball;
private var _vx:Number;
private var _vy:Number;
public function DocumentMain():void
{
_vx = 10;
_vy = 0;
_ball.buttonMode = true;
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function enterFrameHandler(e:Event):void
{
// gravitate the ball
_vy += GRAVITY;
// move the ball
_ball.x += _vx;
_ball.y += _vy;
// check boundaries for collusion
checkBoundaryCollisions();
}
private function mouseDownHandler(e:MouseEvent):void
{
//hit the ball if it has been clicked
if (e.target == _ball)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollisions():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = _ball.x - (_ball.width / 2);
right = _ball.x + (_ball.width / 2);
bottom = _ball.y + (_ball.height / 2);
top = _ball.y - (_ball.height / 2);
if (left < 0 && _vx < 0)
{
_ball.x = _ball.width / 2;
_vx *= -1;
}
else if (right > stage.stageWidth && _vx > 0)
{
_ball.x = stage.stageWidth - (_ball.width / 2);
_vx *= -1;
}
if (top < 0 && _vy < 0)
{
_ball.y = _ball.height / 2;
_vy *= -1;
}
else if (bottom > stage.stageHeight && _vy > 0)
{
_ball.y = stage.stageHeight - (_ball.height / 2);
_vy *= -BOUNCE_FACTOR;
_vx *= BOUNCE_FACTOR;
if (Number(_bounces.text) > Number(_highscore.text))
{
_highscore.text = _bounce.text;
}
_bounces.text = "0";
}
}
private function hit(hitX:Number, hitY:Number):void
{
//increment bounces
_bounces.text = String.(Number(_bounces.text) + 1);
//adjust the vertical velocity of the ball
if (_vy > 0)
{
_vy *= -BOUNCE_FACTOR / 2 ;
}
_vy -= HIT_FORCE;
//adjust the horizontaly velocity of the ball
if (_vx * hitX > 0)
{
_vx *= -BOUNCE_FACTOR;
}
_vx -= ( 2 * hitX / _ball.width) * HIT_FORCE;
}
}
}
}
get rid of the last curly brace }. You have too many at the end of the file.
I also think you mean Actionscript 3.

Flash - using multiple event handlers?

so I'm working on a game which uses multiple .as files - and I'm trying to program the game however it keeps kicking back the following error when it reaches line 21 in theGame.as - the error is...
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at theGame()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\theGame.as:21]
at main/changeState()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\main.as:23]
at mainMenu/brnP_Button()[M:\Users\----\Documents\Programming For Fun\Flash\Tutorial - Menu System\mainMenu.as:40]
Cannot display source code at this location.
I'm using the following .as files.
main.as
//main.as
package
{
import flash.display.*;
import flash.system.fscommand;
public class main extends MovieClip
{
public function main()
{
changeState(null, "menu");
}
public function changeState (currentState, nextState)
{
if (currentState != null)
{
removeChild(currentState);
}
switch(nextState)
{
case "menu": var mm:mainMenu = new mainMenu(changeState);
addChild(mm);
break;
case "game": var g:theGame = new theGame(changeState);
addChild(g);
break;
case "exit": fscommand("quit");
break;
}
}
}
}
mainMenu.as
`
//mainMenu.as
package
{
import flash.display.*;
import flash.events.*;
public class mainMenu extends MovieClip
{
var theCallBackFunction:Function;
private var ballX:Number = 10; // Declaring a variable known as ballX
private var ballY:Number = 0; // Declaring a variable knwon as ballY
private const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const ROTATION:Number = 1;
public const BOUNCE:Number = 0.9;
var gameBall:Ball = new Ball();
public function mainMenu(callBack)
{
addEventListener(Event.ENTER_FRAME, menuFrameHandler);
addChild(gameBall);
var btnPlay:mmPlay = new mmPlay();
btnPlay.addEventListener(MouseEvent.MOUSE_DOWN, brnP_Button);
btnPlay.x = width/2;
btnPlay.y = height/2 - btnPlay.height/2;
addChild(btnPlay);
var btnExit:mmExit = new mmExit();
btnExit.addEventListener(MouseEvent.MOUSE_DOWN, brnE_Button);
btnExit.x = width/2;
btnExit.y = height/2 - btnExit.height/2;
btnExit.y += btnExit.height + 4;
addChild(btnExit);
theCallBackFunction = callBack;
}
public function brnP_Button(e:MouseEvent)
{
removeEventListener(Event.ENTER_FRAME, menuFrameHandler);
theCallBackFunction(this, "game");
return;
}
public function brnE_Button(e:MouseEvent)
{
theCallBackFunction(this, "exit");
return;
}
private function menuFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
checkBoundaryCollision();
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y;
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
else if (bottom > stage.stageHeight && ballY > 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
}
}
}
}
theGame.as
//theGame.as
package
{
import flash.display.MovieClip
import flash.text.TextField
import flash.events.Event
import flash.events.MouseEvent
public class theGame extends MovieClip
{
public const GRAVITY:Number = 2; // Declaring a const variable known as gravity
public const BOUNCE:Number = 0.8;
public const HIT:Number = 15;
public const ROTATION:Number = 1;
public var gameBall:Ball;
private var ballX:Number; // Declaring a variable known as ballX
private var ballY:Number; // Declaring a variable knwon as ballY
public function theGame(callBack): void
{
addChild(gameBall);
ballX = Math.random(); // Initalising ballX
ballY = Math.random(); // Initalising ballY
gameBall.buttonMode = true;
addEventListener(Event.ENTER_FRAME, gameFrameHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
}
private function gameFrameHandler (e:Event):void
{
// Gravitate the Ball
ballY += GRAVITY; // The ball is effected by gravity each frame
// Move The Ball
gameBall.x += ballX;
gameBall.y += ballY;
gameBall.rotation += ROTATION * ballX;
// Check Stage Boundaries For Collisions
checkBoundaryCollision();
}
private function mouseDownHandler (e:MouseEvent):void
{
// Hit the ball if it has been clicked
if (e.target == gameBall)
{
hit(e.target.mouseX, e.target.mouseY);
}
}
private function checkBoundaryCollision():void
{
var left:Number;
var right:Number;
var bottom:Number;
var top:Number;
left = gameBall.x - (gameBall.width / 2);
right = gameBall.x + (gameBall.width / 2);
bottom = gameBall.y + (gameBall.height / 2);
top = gameBall.y - (gameBall.height / 2);
if (left < 0 && ballX < 0)
{
gameBall.x = (gameBall.width / 2)
ballX *= -1;
}
else if (right > stage.stageWidth && ballX > 0)
{
gameBall.x = stage.stageWidth - (gameBall.width / 2)
ballX *= -1;
}
if (top < 42.70 && ballY < 0)
{
gameBall.y = 42.70 + (gameBall.height / 2)
ballY *= -1;
}
else if (bottom > stage.stageHeight && ballY >= 0)
{
gameBall.y = stage.stageHeight - (gameBall.height/2)
ballY *= -BOUNCE;
ballX *= BOUNCE;
}
}
private function hit(hitX:Number, hitY:Number):void
{
// Adjust vertical velocity
if (ballY > 0)
{
ballY *= -BOUNCE / 2;
}
ballY -= HIT;
//adjust horizontal veloity
if (ballX * hitX > 0)
{
ballX *= -BOUNCE;
}
ballX -= (hitX / gameBall.width * HIT);
}
}
}
How would I go about fixing this?
You don't have an instance of gameBall inside your class theGame.
Try adding
gameBall = new Ball();
before
addChild(gameBall);