Making a simple chase AI in AS3 - actionscript-3

im attempting to make a simple game where zombies spawn out randomly from the edges of the screen and once they have spawned, they will get the last position of the player and keep moving towards that direction until they hit the stage and gets removed. However, i seem to be having a problem with the chase code. Even after reading tons of articles that offer the same chunk of code, im still unable to make it work (IM DOING IT WRONG ARRGH).
This is the main class
package
{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
public class main extends MovieClip
{
private var left,right,up,down,fire,mouseRight,mouseLeft:Boolean;
private var speedX,speedY,mobPosX,mobPosY:int;
private var num:Number;
private var wizard:Player;
private var crosshair:Crosshair;
private var mobArray,magicArray:Array;
public function main()
{
//Hide mouse for crosshair
Mouse.hide();
crosshair = new Crosshair();
addChild(crosshair);
crosshair.x = stage.stageWidth;
crosshair.y = stage.stageHeight;
//Set initial speed
speedX = 0;
speedY = 0;
//Wizard stuff
fire = false;
wizard = new Player();
addChild(wizard);
wizard.x = stage.stageWidth / 2;
wizard.y = stage.stageHeight / 2;
//Mob stuff
mobArray = new Array();
magicArray = new Array();
//Initialize bool so movement doesn't get stuck on startup
up = false;
down = false;
left = false;
right = false;
}
public function startGame()
{
addEventListener(Event.ENTER_FRAME,update);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.addEventListener(MouseEvent.CLICK, myClick);
}
private function keyDownHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = true;
}
if (evt.keyCode == 38)
{
up = true;
}
if (evt.keyCode == 39)
{
right = true;
}
if (evt.keyCode == 40)
{
down = true;
}
if (evt.keyCode == 67)
{
trace(mobArray.length);
}
}
private function keyUpHandler(evt:KeyboardEvent)
{
if (evt.keyCode == 37)
{
left = false;
speedX = 0;
}
if (evt.keyCode == 38)
{
up = false;
speedY = 0;
}
if (evt.keyCode == 39)
{
right = false;
speedX = 0;
}
if (evt.keyCode == 40)
{
down = false;
speedY = 0;
}
}
function myClick(eventObject:MouseEvent)
{
fire = true;
}
public function update(evt:Event)
{
//UI
crosshair.x = mouseX;
crosshair.y = mouseY;
//Start player
if (left && right == false)
{
speedX = -8;
}
if (up && down == false)
{
speedY = -8;
}
if (down && up == false)
{
speedY = 8;
}
if (right && left == false)
{
speedX = 8;
}
wizard.x += speedX;
wizard.y += speedY;
for (var i = mobArray.length - 1; i >= 0; i--)
{
//Start mob //if X is zero and Y > 10, spawn.
var m:Zombie = new Zombie();
m.chase((Math.atan2(mobArray[i].y - wizard.y,mobArray[i].x - wizard.x)/Math.PI * 180)); //applies trigo
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
m.x = mobPosX;
m.y = mobPosY;
mobArray.push(m);
addChild(m);
}
}
private function gameOver()
{
removeEventListener(Event.ENTER_FRAME,update);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
}
}//end class
}//end package
This is the zombie class
package
{
import flash.display.*;
import flash.events.*;
public class Zombie extends MovieClip
{
private var zombSpd:Number;
private var angle:Number;
public function Zombie()
{
zombSpd = 10;
}
public function chase(chaseAngle:Number)
{
angle = chaseAngle;
}
public function update()
{
this.x+=Math.cos(angle*Math.PI/180)*zombSpd;
this.y+=Math.sin(angle*Math.PI/180)*zombSpd;
}
}//end class
}//end package
Thank you :)

I just reread your code and see that you must read and learn more about programming before trying to create a game like this.
the reason your zombies are not spawning are because you never get inside the for loop. mob array length will be zero to start with, so the for loop will never happen.
take that for loop out and create a function to spawn enemies in your main class. you can use the code you use in your for loop as the code for this function example:
function spawn():void{
//code directly from your for loop, with a small change
num = Math.random();
if (num < 0.1)
{
//when x = 0
mobPosX = 10;
mobPosY = Math.floor(Math.random() * 590) + 10;
}
else if (num < 0.3)
{
//when y = 0
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 10;
}
else if (num < 0.6)
{
mobPosX = 800;
mobPosY = Math.floor(Math.random() * 590) + 10;
//when x width of screen
}
else if (num < 0.9)
{
//y is height of screen
mobPosX = Math.floor(Math.random() * 790) + 10;
mobPosY = 590;
}
var m:Zombie = new Zombie();
m.x = mobPosX;
m.y = mobPosY;
m.chase((Math.atan2(m.y - wizard.y,m.x - wizard.x)/Math.PI * 180)); //applies trigo
mobArray.push(m);
addChild(m);
}
now in your update function you must determine when you want enemies to spawn. you can do this by using a counter. Ill let you figure that part out, but if you want zombies to spawn continuously, (where your forloop in the update function was) add this:
//use a counter variable to determine when to execute spawn
spawn();
//loop through all zombies
for(var i:int = 0; i < mobArray.length; i++){
mobArray[i].update();
}

Steering behavior example at AdvanceEDActionScriptAnimation with abstracted interfaces and marshaling implementation.
Github:https://github.com/yangboz/as3SteeringBehavior

Related

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();
}

Bullet fires perfectly in three directions, but not left

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;
}

1046 AS3 Compile Time Error

I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
function moveBullets():void
{
for (var i:int = 0; i < bullets.length; i++)
{
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x <-bullets[i].width
|| bullets[i].x > stage.stageWidth + bullets[i].width
|| bullets[i].y < -bullets[i].width
|| bullets[i].y > stage.stageHeight + bullets[i].width)
{
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
function moveBaddies():void
{
for (var i:int = 0; i < baddies.length; i++)
{
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.

How can I set the damage level of enemy

Thanks in advance...
I am having little bit doubt in my logic for setting the Damage level to the enemy in game. Following is my Enemy Class
package scripts.enemy
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Stage;
public class Enemy1 extends MovieClip
{
private var BG:MovieClip;
private var speed:Number = 0.5;
private var ease:Number = .005;
private var rad:Number = 57.2957795;
public function Enemy1(BG:MovieClip) : void
{
var RandomX:Array = new Array(-150,-200,-250,-300,-350,-400,-450,-500,-550,150,200,250,300,350,400,450,500,550);
var RandomY:Array = new Array(-150,-200,-250,-300,-350,-400,150,200,250,300,350,400);
var r:int = (Math.random() * 18);
var s:int = (Math.random() * 12);
x = RandomX[r];
y = RandomY[s];
this.BG = BG;
addEventListener(Event.ENTER_FRAME, moveEnemy); //false, 0, true);.
}
private function moveEnemy(e:Event):void
{
var dx:Number = x - 10;
var dy:Number = y - 10;
this.x -= dx * ease;
this.y -= dy * ease;
this.rotation = (Math.atan2(dy,dx) * rad) + 180;
}
}
}
And Here is some of code that giving me trouble from my Main class
// ......... Function for Checking the Collision between Bullet And Enemy...........
private function checkCollision(mc:MovieClip):Boolean
{
var test:Point = mc.localToGlobal( new Point());
for (var i = 0; i < enemies1.length; i++)
{
tempEnemy1 = enemies1[i];
if (kill == true)
{
if (tempEnemy1.hitTestPoint(test.x,test.y,true))
{
enemies1.splice(i, 1);
bg_mc.removeChild(tempEnemy1);
createDead(Dead1,deadArray1,tempEnemy1.x,tempEnemy1.y,tempEnemy1.rotation);
Score += 10;
Scr_txt.text = String(Score);
bugsKill += 1;
kill = false;
return true;
}
}
}
if (Level >= 2)
{
for (var j = 0; j < enemies2.length; j++)
{
tempEnemy2 = enemies2[j];
if (kill == true)
{
if (tempEnemy2.hitTestPoint(test.x,test.y,true))
{
bug2HitCount -= 1;
if (bug2HitCount == 0)
{
enemies2.splice(j, 1);
bg_mc.removeChild(tempEnemy2);
createDead(Dead2,deadArray2,tempEnemy2.x,tempEnemy2.y,tempEnemy2.rotation);
Score += 20;
Scr_txt.text = String(Score);
bugsKill += 1;
kill = false;
//bug2HitCount = bug2HitRate;
return true;
}
kill = false;
return true;
}
}
}
}
return false;
}
private function removeElement(removeList:Array):void
{
for (var i = 0; i < removeList.length; i++)
{
bg_mc.removeChild(removeList[i]);
}
}
//...........Function Checking the Collission Between Bunker And Enemy..............
private function collideEnemy(deadArray:Array,enemyArray:Array,rate:Number):void
{
var enemy:MovieClip;
for (var i = 0; i < enemyArray.length; i++)
{
enemy = enemyArray[i];
if (enemy.hitTestObject(bunker_mc))
{
life_mc.scaleX -= rate;
if (life_mc.scaleX <= 0.05)
{
stage.removeEventListener(Event.ENTER_FRAME,updateCollission);
Timer1.stop();
Mouse.show();
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUpFun);
stage.removeEventListener(Event.ENTER_FRAME,updateStage);
stage.removeEventListener(MouseEvent.MOUSE_DOWN,mouseDownFun);
(player.parent).removeChild(player);
(bunker_mc.parent).removeChild(bunker_mc);
(life_mc.parent).removeChild(life_mc);
(sniper_mc.parent).removeChild(sniper_mc);
removeElement(bullets);
EndFun();
gunFire = false;
gotoAndStop("end");
Level = 1;
}
}
}
}
//...........function of Timer Complete Event.....................
private function TimerEnd(e:TimerEvent):void
{
EndBug();
gotoAndStop("end");
}
//...........function of Timer Complete Event.....................
private function EndBug():void
{
HelpTimer = new Timer(1000,1);
HelpTimer.addEventListener(TimerEvent.TIMER_COMPLETE,HelpFun);
HelpTimer.start();
stage.removeEventListener(Event.ENTER_FRAME,updateStage);
stage.removeEventListener(Event.ENTER_FRAME,updateCollission);
function HelpFun(Event:TimerEvent)
{
stage.removeEventListener(MouseEvent.MOUSE_UP,mouseUpFun);
stage.removeEventListener(MouseEvent.MOUSE_DOWN,mouseDownFun);
gunFire = false;
bg_mc.removeChild(player);
bg_mc.removeChild(bunker_mc);
(life_mc.parent).removeChild(life_mc);
bg_mc.removeChild(sniper_mc);
EndFun();
Score = 0;
Level += 1;
totalBugs += 5;
}
}
//..................Function for ending the Game And removing the Reamining Enemies.................
private function EndFun():void
{
Mouse.show();
removeElement(dustArray);
if (Level == 1)
{
removeElement(enemies1);
removeElement(deadArray1);
gotoAndStop("level2");
}
if (Level == 2)
{
removeElement(enemies1);
removeElement(deadArray1);
removeElement(enemies2);
removeElement(deadArray2);
gotoAndStop("level3");
}
if (Level == 3)
{
......
}
.....................
.....................
}
}
}
In this code I have added a new type of Enemy in Level 2 and I have also written code for its HitTest property..In which each enemy of level 2 requires more than 1 bullet to kill.. But when I shoot a bullet to one enemy and then I shoot another bullet to another enemy of same type the another enemy gets killed. It means that the second enemy is getting killed in only 1 single bullet.. So how can I solve this issue..?
Please Help.. Thanks in advance..
The problem in your code lies within the checkCollision function. It basically goes over the first for loop and ignores the second. But it's best if you just assign the enemies health by adding a health parameter within your Enemy class and have each bullet decrease their health by 1. That way, you can just go through your array and remove any enemies that reach 0 health.
EDIT: I just looked over your code again and realized it's the bug2HitCount that's screwing everything up.

Can anyone help with the collision detect for my platformer? (Actionscript 3.0)

Im currently working on making a flash platformer engine...but my collision detect needs some serious help. Whenever my character 'jumps', and lands on the collision object, he goes about halfway through it for a split second, then goes back to the top (where I want him to be). If I continue to jump multiple times, the shadow of him, if you will, that appears for a split second goes further and further into the collision object, eventually making him fall all the way through it. Here's the code for my main class, and if you need me to clarify anything, please ask.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.display.Stage;
import Player;
import HitObject;
public class TestGame extends MovieClip {
private var _hitObject:HitObject;
private var _player:Player;
private var _leftArrow:Boolean;
private var _rightArrow:Boolean;
private var _upArrow:Boolean;
private var _hit:Boolean;
private var _fall:Boolean;
private var _jump:Boolean = true;
private var _velR:Number = 0;
private var _velL:Number = 0;
private var _scale:Number = .1;
private var _jumpCount:Number = 0;
private var _i:Number = .5;
private var _i2:Number = 7;
private var _i3:Number = 0;
private var _adjustHit:Number;
private var _jumpRL:Number;
private var _jumpVel:Number;
public function TestGame() {
_hitObject = new HitObject();
_player = new Player();
addChild(_hitObject);
addChild(_player);
_hitObject.x = (stage.width * 0.5) + 50;
_hitObject.y = (stage.height * 0.5) + 150;
_hitObject.scaleY = 3;
_hitObject.alpha = .5;
_player.scaleX = _scale;
_player.scaleY = _scale;
_player.x += 200;
_player.y += 250;
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
}
private function enterFrameHandler(e:Event) {
if(_player.hitTestObject(_hitObject)) {
_adjustHit = _hitObject.y - _hitObject.height/2 - _player.height/2;
_player.y = _adjustHit;
_hit = true;
_jump = false;
if(_i3 > 8) {
_jump = true;
}
_jumpCount = 0;
_i2 = 7;
_fall = false;
_i3++;
}
else if(!_player.hitTestObject(_hitObject) && !_upArrow) {
_fall = true;
}
if(_fall) {
_player.y += _i;
_i += .5;
if(_i < 3) {
_i = 3;
}
_hit = false;
}
if(_upArrow && _hit && _jump) {
if(_velR > 0) {
_jumpRL = _velR;
_jumpVel = _velR;
}
else if(_velL > 0) {
_jumpRL = -_velL;
_jumpVel = _velL;
}
else {
_jumpVel = 1;
if(_player.scaleX == .1) {
_jumpRL = 1;
}
else {
_jumpRL = -1;
}
}
_player.y -= _i2 + _jumpVel/2;
_player.x += _jumpRL/2;
_jumpCount += _i2;
_i2 -= .5;
_fall = false;
if(_i2 < -3) {
_jumpCount = 61;
}
if(_jumpCount > 60) {
_i2 = 7;
_jump = false;
_fall = true;
_jumpCount = 0;
}
_i3 = 0;
}
if(_rightArrow) {
_player.startRun();
_player.scaleX = _scale;
_velL = 0;
_player.x += _velR;
if(_velR < 20) {
_velR += 2;
}
if(_velR > 20) {
_velR = 20;
}
}
else if(_leftArrow) {
_player.startRun();
_player.scaleX = -_scale;
_velR = 0;
_player.x -= _velL;
if(_velL < 20) {
_velL += 2;
}
if(_velL > 20) {
_velL = 20;
}
}
if(_velR > 0) {
_player.x += _velR;
_velR -= .7;
}
else if(_velL > 0) {
_player.x -= _velL;
_velL -= .7;
}
if(_velR < 0 || _velL < 0) {
_velR = 0;
_velL = 0;
}
}
private function keyDownHandler(e:KeyboardEvent):void {
if(e.keyCode == 39) {
_rightArrow = true;
}
if(e.keyCode == 37) {
_leftArrow = true;
}
if(e.keyCode == 38) {
_upArrow = true;
}
}
private function keyUpHandler(e:KeyboardEvent):void {
_upArrow = false;
_rightArrow = false;
_leftArrow = false;
}
}
}
For anyone having this problem, make sure you are applying a force in response to collision in addition to repositioning out of collision. This case sounds like maybe the velocity is being compounded by gravity, meaning you keep moving the object back but it's velocity isn't being zeroed out, so it moves further and further into the floor with each update step.
Applying normal force will cancel gravity and fix this.
If you just want easy-to-use collision detection, take a look at the Collision Detection Kit for Actionscript 3. I've used it before and it beats every other collision detection framework I've ever used.
From what you have said it sounds like at time 't' the player has not hit the object as yet but at time 't+1' the player has moved 10px (for example) so now appears stuck in the object until your collision handler moves the player to the correct spot.
Also with the jumping up and down perhaps the player has not been moved back correctly after a collision before his position increments which is why over time the player eventually falls through if you keep jumping.
Be careful about comparing numbers. I see a if (_player.scaleX == .1). Numbers in AS3 are called Floating Point numbers in other languages. Due to the way Floating Point numbers are handled by the computer they can give misleading results. Sometimes a value like 1.0 is really 0.999998 and if thats the case a compare statement will always fail.
As a tip you might want to change some of the values to CONST as you have a lot of hardcoded values, some which are related and could be changed easier by making them a CONST.