AS3 changing between animation states - actionscript-3

I am having troubles coding the animation state changes in flash. I have a little big planet style game with 3 horizontal rows the character can jump between. I have the motion set-up in a tween, but I haven't been able to get the character to transition from running animation to jump back/jump forward animation, and then back to run animation when it has finished transitioning between the layers.
The run animation frames are from 1 - 60, jump back a layer is 61, and jump forward a layer is 62. I haven't begun to worry about stationary yet, so it has no frames.
Edit: I've removed the anmatePlayer function and moved the animation control code into the checkEveryFrame function. I only made a separate function for the animations because I wasn't sure where it should go.
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
public class Main_Test_2 extends MovieClip
{
// variables
private var cam:MovieClip = new MovieClip();
private var player:Player = new Player();
private var topPosition:uint = 250;
private var centerPosition:uint = 430;
private var bottomPosition:uint = 610;
private var tweenSpeed:Number = 0.33;
private var UI:UserInterface = new UserInterface();
public function Main_Test_2():void
{
// initialize
init();
}
public function init():void
{
// initialize variables
stage.addChild (cam);
player.x = 200;
player.y = bottomPosition;
cam.addChild (UI);
cam.addChild (player);
// add event listeners
stage.addEventListener(Event.ENTER_FRAME, checkEveryFrame);
UI.topButton.addEventListener(MouseEvent.CLICK, topButtonClick);
UI.centerButton.addEventListener(MouseEvent.CLICK, centerButtonClick);
UI.bottomButton.addEventListener(MouseEvent.CLICK, bottomButtonClick);
}
public function checkEveryFrame(event:Event):void
{
cam.x -= player.x - player.x;
cam.y -= player.y - player.y;
player.vx = player.x - player.prevX;
player.vy = player.y - player.prevY;
player.prevX = player.x;
player.prevY = player.y;
/*if (player.y != topPosition || player.y != centerPosition || player.y != topPosition)
{
player.gotoAndStop (61);
}
else if (player.y == topPosition || player.y == centerPosition || player.y == topPosition)
{
player.gotoAndStop (1);
}*/
if (player.currentFrame == 60)
{
player.gotoAndStop (1);
}
else if (player.currentFrame < 60)
{
player.gotoAndStop (player.currentFrame + 1);
}
/*if (player.y < player.prevY)
{
player.gotoAndStop (61);
}
else if (player.y > player.prevY)
{
player.gotoAndStop (62);
}
else if (player.vy == 0)
{
player.gotoAndStop (1);
}*/
}
public function topButtonClick (event:MouseEvent):void
{
trace ("Top Click");
if (player.y >= bottomPosition)
{
var tween01:Tween = new Tween (player, "y", None.easeNone, bottomPosition, centerPosition, tweenSpeed, true);
}
else if (player.y == centerPosition)
{
var tween02:Tween = new Tween (player, "y", None.easeNone, centerPosition, topPosition, tweenSpeed, true);
}
else if (player.y < topPosition)
{
player.y = topPosition;
}
}
public function centerButtonClick (event:MouseEvent):void
{
trace ("Center Click");
if (player.y > centerPosition)
{
var tween01:Tween = new Tween (player, "y", None.easeNone, bottomPosition, centerPosition, tweenSpeed, true);
}
else if (player.y < centerPosition)
{
var tween03:Tween = new Tween (player, "y", None.easeNone, topPosition, centerPosition, tweenSpeed, true);
}
}
public function bottomButtonClick (event:MouseEvent):void
{
trace ("Bottom Click");
if (player.y <= topPosition)
{
var tween03:Tween = new Tween (player, "y", None.easeNone, topPosition, centerPosition, tweenSpeed, true);
}
else if (player.y == centerPosition)
{
var tween4:Tween = new Tween (player, "y", None.easeNone, centerPosition, bottomPosition, tweenSpeed, true);
}
else if (player.y > bottomPosition)
{
player.y = bottomPosition;
}
}
}
}

It would be helpful to see the code that actually calls animatePlayer; regardless, below is a solution.
Rather than rely on MovieClip to animate, you handle it in your existing checkEveryFrame, thereby providing you more exact control to change your animation state exactly when you need to. I've taken the liberty of unifying your UI clicking actions into a more maintainable function. Additionally, with the absence of your keybinding function, I've added playerState changes to the UI clicking for the sake of demonstration.
As best as I can tell, this should compile, but I'm unable to attempt it without the rest of your objects.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
public class Main_Test_2 extends MovieClip
// variables
private var cam:MovieClip = new MovieClip();
private var player:Player = new Player();
private var tweenSpeed:Number = 0.33;
private var UI:UserInterface = new UserInterface();
public function Main_Test_2():void {
// initialize
init();
}
public function init():void {
// initialize variables
stage.addChild(cam);
player.x = 200;
player.y = playerTracks[0];
cam.addChild(UI);
cam.addChild(player);
// add event listeners
stage.addEventListener(Event.ENTER_FRAME, checkEveryFrame);
UI.topButton.addEventListener(MouseEvent.CLICK, movePlayer);
UI.centerButton.addEventListener(MouseEvent.CLICK, movePlayer);
UI.bottomButton.addEventListener(MouseEvent.CLICK, movePlayer);
}
public function checkEveryFrame(event:Event):void {
cam.x -= player.x - player.x;
cam.y -= player.y - player.y;
player.vx = player.x - player.prevX;
player.vy = player.y - player.prevY;
player.prevX = player.x;
player.prevY = player.y;
// Animation control
var a:Array = animations[playerState]; // current animation set
if (a.length == 2) {
var maxFrames:int = a[1] - a[0]; // Normalize the max value
var currentFrame:int = player.currentFrame - a[0]; // Normalize the current value
var nextFrame:int = normalizedCurrentFrame%maxFrames + a[0] // Modulus of max, and return to actual
player.gotoAndStop(nextFrame)
}
}
private var playerState:String = "run";
private var animations:Object = {
"run":[1,60],
"jump":[61],
"jumpForward":[62]
}
private var playerTracks:Array = [610, 430, 250];
private var playerLocIndex:int = 0;
public function movePlayer(e:MouseEvent):void {
// Based on the button clicked, increase/decrease/set the index of the destination
switch (e.currentTarget) {
case UI.topButton:
playerState = "jump";
playerLocIndex++;
if (playerLocIndex > 2) { playerLocIndex = 2; } // Clamp upper
break;
case UI.centerButton:
playerState = "run";
playerLocIndex = 1;
break;
case UI.bottomButton:
playerState = "jumpForward";
playerLocIndex--;
if (playerLocIndex < 0) { playerLocIndex = 1; } // Clamp lower
break;
}
new Tween(player, "y", None.easeNone, player.y, playerTracks[playerLocIndex], tweenSpeed, true);
}
}
}

Ok, I solved the problem. I had to use a timer that executed its action after the timer ran out. I placed it and a line of code to change states in each line of code with the tweens so the animation would go from run to the jump forward/backward animation and back to run at the end of the timer. Hope this helps someone else in the future.

Related

Having an issue with Flash Actionscript3

Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the sheep to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
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;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);

AS3 Frogger Pixel Perfect Collision

I have created a simple AS3 frogger game and used .hitTestObject to test if the frog hits any of the obstacles. This is not effective as the frog hits objects that aren't touching it at all. I am new to AS3 and have no idea where to start with coding for this. Any help would be appreciated!
package {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.utils.Timer;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class Main extends MovieClip
{
//set variables
public var frog_spriteInstance:frog_sprite;
public var safeZoneInstance1 : safeZone;
public var safeZoneInstance2: safeZone;
public var safeZoneInstance3 : safeZone;
public var whitecar : car1;
public var whitecar1 : car1;
public var whitecar2 : car1;
public var truck1 : truck_sprite;
public var truck2: truck_sprite;
public var redcar : car_sprite;
public var redcar2 : car_sprite;
public var redcar3 : car_sprite;
public var log1 : log_sprite;
public var log2 : log_sprite;
public var log3 : log_sprite;
public var letters : Letters;
public var letters2 : Letters_2;
public var letters3 : Letters_3;
public var letters4 : Letters_4;
public var health : HealthBar;
public var firstletter : firstLetter;
public var secondletter : secondLetter;
public var thirdletter : thirdLetter;
public var fourthletter : fourthLetter;
var mysound:Sound = new (mySound);
public function Main()
{
// constructor code
safeZoneInstance1 = new safeZone();
stage.addChild(safeZoneInstance1);
safeZoneInstance1.x = 300;
safeZoneInstance1.y=545
safeZoneInstance2 = new safeZone();
stage.addChild(safeZoneInstance2);
safeZoneInstance2.x = 300;
safeZoneInstance2.y=300
safeZoneInstance3 = new safeZone();
stage.addChild(safeZoneInstance3);
safeZoneInstance3.x = 300;
safeZoneInstance3.y=100
whitecar = new car1();
stage.addChild(whitecar);
whitecar.x = 300;
whitecar.y = 500
whitecar1 = new car1();
stage.addChild(whitecar1);
whitecar1.x = 550;
whitecar1.y = 480
whitecar2 = new car1();
stage.addChild(whitecar2);
whitecar2.x = 50;
whitecar2.y = 480
truck1 = new truck_sprite();
stage.addChild (truck1);
truck1.x = 1000;
truck1.y = 430
truck2 = new truck_sprite();
stage.addChild (truck2);
truck2.x = 300;
truck2.y = 430
redcar = new car_sprite();
stage.addChild (redcar);
redcar.x = 300;
redcar.y = 340
redcar2 = new car_sprite();
stage.addChild (redcar2);
redcar2.x = 100;
redcar2.y = 375
redcar3 = new car_sprite();
stage.addChild (redcar3);
redcar3.x = 500;
redcar3.y = 375
log1 = new log_sprite();
stage.addChild(log1);
log1.x = 300;
log1.y = 230
log2 = new log_sprite();
stage.addChild(log2);
log2.x = 100;
log2.y = 150
log3 = new log_sprite();
stage.addChild(log3);
log3.x = 500;
log3.y = 150
letters = new Letters();
letters.x = randomRange(100,500) ;
letters.y = randomRange(100,500);
stage.addChild(letters);
letters2 = new Letters_2();
letters2.x = randomRange(100,500) ;
letters2.y = randomRange(100,500);
stage.addChild(letters2);
letters3 = new Letters_3();
letters3.x = randomRange(100,500) ;
letters3.y = randomRange(100,500);
stage.addChild(letters3);
letters4 = new Letters_4();
letters4.x = randomRange(100,500) ;
letters4.y = randomRange(100,500);
stage.addChild(letters4);
frog_spriteInstance = new frog_sprite();
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
health = new HealthBar();
stage.addChild(health);
health.x = 130;
health.y = 20;
health.width = 100;
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.addEventListener(Event.ENTER_FRAME, movecars);
stage.addEventListener(Event.ENTER_FRAME, movetrucks);
stage.addEventListener(Event.ENTER_FRAME, moveredcars);
stage.addEventListener(Event.ENTER_FRAME, movelogs);
stage.addEventListener(Event.ENTER_FRAME,checkforcollision);
mysound.play();
}
public function moveFrog(e:KeyboardEvent)
{
// get the key pressed and then move the player
{
if (e.keyCode == Keyboard.UP)
{
frog_spriteInstance.rotation = 0;
frog_spriteInstance.y -= 50;
}
if (e.keyCode == Keyboard.DOWN)
{
frog_spriteInstance.rotation = 180;
frog_spriteInstance.y += 50;
}
if (e.keyCode == Keyboard.LEFT)
{
frog_spriteInstance.rotation = -90;
frog_spriteInstance.x -= 50;
}
if (e.keyCode == Keyboard.RIGHT)
{
frog_spriteInstance.rotation = 90;
frog_spriteInstance.x += 50;
}
}
}
function movecars(event:Event)
{
//move cars across screen and when they disappear, reappear at the other side
whitecar.x -= 3;
if (whitecar.x<-100){
whitecar.x=650;
}
whitecar1.x -= 3;
if (whitecar1.x<-100){
whitecar1.x=650;
}
whitecar2.x -= 3;
if (whitecar2.x<-100){
whitecar2.x=650;
}
}
function movelogs(event:Event)
{
//move logs across screen and when they disappear, reappear at the other side
log1.x -= 5;
if (log1.x<-100){
log1.x=650;
}
log2.x -= 5;
if (log2.x<-100){
log2.x=650;
}
log3.x -= 5;
if (log3.x<-100){
log3.x=650;
}
}
function movetrucks(event:Event)
{
//move trucks across screen and when they disappear, reappear at the other side
truck1.x +=3;
if (truck1.x>650){
truck1.x=-100;
}
truck2.x +=3;
if (truck2.x>650){
truck2.x=-100;
}
}
function moveredcars(event:Event)
{
//move red cars across screen and when they disappear, reappear at the other side
redcar.x +=3;
if (redcar.x>650){
redcar.x=-100;
}
redcar2.x +=3;
if (redcar2.x>650){
redcar2.x=-100;
}
redcar3.x +=3;
if (redcar3.x>650){
redcar3.x=-100;
}
}
function checkforcollision(event:Event)
{
//check for collisions
if (frog_spriteInstance.hitTestObject(log1) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(log3) || (frog_spriteInstance.hitTestObject(whitecar) || (frog_spriteInstance.hitTestObject(whitecar1) || (frog_spriteInstance.hitTestObject(whitecar2) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(truck1) || (frog_spriteInstance.hitTestObject(truck2) || (frog_spriteInstance.hitTestObject(redcar) || (frog_spriteInstance.hitTestObject(redcar2) || (frog_spriteInstance.hitTestObject(redcar3))))))))))))){
//reset frog if hits an obstacle
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
//reduce health bar
health.width -= 10;
}
//remove event listeners when health is empty
if (health.width == 0){
stage.removeEventListener(Event.ENTER_FRAME, movecars);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.removeEventListener(Event.ENTER_FRAME, movetrucks);
stage.removeEventListener(Event.ENTER_FRAME, moveredcars);
stage.removeEventListener(Event.ENTER_FRAME, movelogs);
}
//add letters to bottom of screen when hit correctly
if (frog_spriteInstance.hitTestObject(letters)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters);
firstletter = new firstLetter();
stage.addChild(firstletter);
firstletter.x=345;
firstletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters2)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters2);
secondletter = new secondLetter();
stage.addChild(secondletter);
secondletter.x=206;
secondletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters3)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters3);
thirdletter = new thirdLetter();
stage.addChild(thirdletter);
thirdletter.x=273;
thirdletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters4)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters4);
health.width -= 10;
fourthletter = new fourthLetter();
stage.addChild(fourthletter);
fourthletter.x=25;
fourthletter.y=620;
}
}
function randomRange(minNum:Number, maxNum:Number):Number
{
//random generator for letter positioning
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
}
}
Also my code is pretty dodgy so any suggestions on improvement are very welcome.
To perform pixel perfect hit test from two arbitrary display objects you have to draw them to bitmaps and use BitmapData/hitTest().
Here is a generalized function that does this:
function hitTestShapes(object1:DisplayObject, object2:DisplayObject, threshold:uint = 1):Boolean {
var bounds1:Rectangle = object1.getBounds(object1.parent);
var matrix1:Matrix = object1.transform.matrix;
matrix1.tx = object1.x - bounds1.x;
matrix1.ty = object1.y - bounds1.y;
var bmp1:BitmapData = new BitmapData(bounds1.width, bounds1.height, true, 0);
bmp1.draw(object1, matrix1);
var bounds2:Rectangle = object2.getBounds(object2.parent);
var matrix2:Matrix = object2.transform.matrix;
matrix2.tx = object2.x - bounds2.x;
matrix2.ty = object2.y - bounds2.y;
var bmp2:BitmapData = new BitmapData(bounds2.width, bounds2.height, true, 0);
bmp2.draw(object2, matrix2);
return bmp1.hitTest(bounds1.topLeft, threshold, bmp2, bounds2.topLeft, threshold);
}
Note, though, that drawing to bitmaps is rather slow, so be careful not to over-use this kind of function or you will have performance issues. In fact, it would be a good idea to use hitTestObject() first, which is very fast and detects bounding box intersections, then only call hitTestShapes() to refine your check. In other words:
if (frog_spriteInstance.hitTestObject(log1) && hitTestShapes(frog_spriteInstance, log1)) { }
As for suggestions on your code, there's a lot of potential for de-duplicating by way of arrays, loops, and functions. For example, instead of defining all your objects as separate variables, just store them all in an array (or vector):
public var safeZones:Array = [];
public var obstacles:Array = [];
public var letters:Array = [];
To populate the arrays, you can push values into them and use a function to consolidate all your duplicate object setup code:
(Code convention note: use "UpperCamelCase" for class names.)
public function Main(){
addSafeZone(300, 545);
addSafeZone(300, 300);
addSafeZone(300, 100);
addObstacle(WhiteCar, 300, 500);
addObstacle(WhiteCar, 550, 480);
addObstacle(WhiteCar, 50, 480);
addObstacle(Truck, 1000, 430);
addObstacle(Truck, 300, 430);
addObstacle(RedCar, 300, 340);
addObstacle(RedCar, 100, 375);
addObstacle(RedCar, 500, 375);
addObstacle(Log, 300, 230);
addObstacle(Log, 100, 150);
addObstacle(Log, 500, 150);
addRandomLetters(Letters_1);
addRandomLetters(Letters_2);
addRandomLetters(Letters_3);
addRandomLetters(Letters_4);
}
private function addSafeZone(x:Number, y:Number):void {
var safeZone:SafeZone = new SafeZone();
stage.addChild(safeZone);
safeZone.x = x;
safeZone.y = y
safeZones.push(safeZone);
}
private function addObstacle(spriteClass:Class, x:Number, y:Number):void {
var obstacle:Sprite = new spriteClass();
stage.addChild(obstacle);
obstacle.x = x;
obstacle.y = y
obstacles.push(obstacle);
}
private function addRandomLetters(lettersClass:Class):void {
var lettersSprite:Sprite = new lettersClass();
lettersSprite.x = randomRange(100, 500);
lettersSprite.y = randomRange(100, 500);
stage.addChild(lettersSprite);
letters.push(lettersSprite);
}
Now you can loop over the arrays to perform all your actions. For example, to check for a hit against any obstacle:
for each(var obstacle:DisplayObject in obstacles){
if(frog.hitTestObject(obstacle) && hitTestShapes(frog, obstacle)){
// The frog hit an obstacle!
}
}
You could also combine all our "move" functions into one, which moves each obstacle based on their type:
private function moveObstacles(e:Event):void {
for each(var obstacle in obstacles){
if(obstacle is WhiteCar){
obstacle.x -= 3;
}
else if(obstacle is RedCar){
obstacle.x += 3;
}
else if(obstacle is Truck){
obstacle.x += 3;
}
else if(obstacle is Log){
obstacle.x -= 5;
}
if(obstacle.x < -100){
obstacle.x = 650;
}
else if(obstacle.x > 650){
obstacle.x = -100;
}
}
}
Lastly, you really should only need a single ENTER_FRAME handler. Just call whatever functions you want from in there. Adding multiple ENTER_FRAME handlers can get troublesome to manage. For example, just do this:
addEventListener(Event.ENTER_FRAME, update);
private function update(e:Event):void {
moveObstacles();
doOtherStuff();
anythingYouNeedToDo();
}
This way you only need to removeEventListener(Event.ENTER_FRAME, update) to stop the game, not a whole bunch of ENTER_FRAME handlers.
I haven't tested any of this code, but you get the general idea. Let me know if you have any issues with it and I can help.

Action Script 3, how to make characters jump?

I am creating a simple 2D platformer in Flash Develop as3 but I don't know how to create a way for my characters to jump.
Here is my code for main.as:
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* ...
* #author Harry
*/
public class Main extends Sprite
{
public var StartButton:Go;
public var FireBoy:Hero;
public var WaterGirl:Female;
public var Door1:Firedoor;
public var Door2:Waterdoor;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
StartButton = new Go();
addChild(StartButton);
StartButton.addEventListener(MouseEvent.CLICK, startgame);
}
private function startgame(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
removeChild(StartButton);
FireBoy = new Hero ();
stage.addChild(FireBoy);
FireBoy.y = 495;
//This allows movement for FireBoy
stage.addEventListener(KeyboardEvent.KEY_DOWN, HandleHeroMove);
WaterGirl = new Female();
stage.addChild(WaterGirl);
WaterGirl.x = 70;
WaterGirl.y = 495;
stage.addEventListener(KeyboardEvent.KEY_DOWN, HandleFemaleMove);
Door1 = new Firedoor();
stage.addChild(Door1);
Door1.x = 5;
Door1.y = 62;
Door2 = new Waterdoor();
stage.addChild(Door2);
Door2.x = 100;
Door2.y = 62;
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 0, 800, 40);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 170, 600, 40);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.moveTo(800, 200);
graphics.lineTo(800, 700);
graphics.lineTo(400, 700);
graphics.lineTo(100, 700);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 580, 800, 40);
graphics.endFill();
}
//This handles FireBoys movement
public function HandleHeroMove(e:KeyboardEvent):void
{
trace(e.keyCode);
//This is for moving to the left
if (e.keyCode == 37)
{
FireBoy.x = FireBoy.x - 30;
Check_Border();
}
//This is for moving to the right
else if (e.keyCode == 39)
{
FireBoy.x = FireBoy.x + 30;
Check_Border();
}
else if (e.keyCode == 38)
{
FireBoy.grav = -15;
}
}
//This handles WaterGirls movement
public function HandleFemaleMove (e:KeyboardEvent):void
{
trace(e.keyCode);
//This is for moving to the left
if (e.keyCode == 65)
{
WaterGirl.x = WaterGirl.x - 30;
Check_Border();
}
//This is for moving to the right
else if (e.keyCode == 68)
{
WaterGirl.x = WaterGirl.x + 30;
Check_Border();
}
else if (e.keyCode == 87)
{
WaterGirl.grav = -15;
}
}
//This stops characters from leaving the screen
public function Check_Border():void
{
if (FireBoy.x <= 0)
{
FireBoy.x = 0;
}
else if (FireBoy.x > 750)
{
FireBoy.x = 750;
}
if (WaterGirl.x <= 0)
{
WaterGirl.x = 0;
}
else if (WaterGirl.x > 750)
{
WaterGirl.x = 750;
}
}
}
}
Here is my code for Hero.as (I have identical code for Female.as):
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
/**
* ...
* #author Harry
*/
public class Hero extends Sprite
{
[Embed(source="../assets/FireBoy.jpg")]
private static const HeroFireBoy:Class;
private var FireBoy:Bitmap;
public var grav:int = 0;
public var floor:int = 580;
public function Hero()
{
FireBoy = new Hero.HeroFireBoy();
scaleX = 0.1;
scaleY = 0.1;
addChild(FireBoy);
}
public function adjust():void
{
FireBoy.y += grav;
if(FireBoy.y+FireBoy.height/2<floor)
grav++;
else
{
grav = 0;
FireBoy.y = floor - FireBoy.height / 2;
}
if (FireBoy.x - FireBoy.width / 2 < 0)
FireBoy.x = FireBoy.width / 2;
if (FireBoy.x + FireBoy.width / 2 > 800)
FireBoy.x = 800 - FireBoy.width / 2;
}
}
}
Please can you suggest exactly what code I should write and where to put it because, I can't find anything helpful and i am getting quite stressed over it.
One way to do is like this: in your Hero.as, you functions like jump, move_left and move_right and keep keep the coordinates within the Hero class. Then call those methods wherever you instantiate your Hero object.
As as example in your main.as, you may execute this code when space bar or up-arrow-key is pressed to make your Hero jump:
var hero:Hero = new Hero();
hero.jump();
If it is a simple jump on Y-axis, then you just have to change the Y-axis value. If it is both X-axis and Y-axis, like a forward jump, then you may consider Trigonometry Sine function to calculate the point on which your character should move to make it look smooth.
You don't need identical Female.as class. What you should do is this: Create a class (probably named Character). Add jump, move_left, move_right functions to this class. And then inherit Character class in Hero.as and Female.as. (You need to Google "inheritance" to learn more about this). Then you can instantiate Hero and Female with the same code that resides in Character class.
You may also need to override in Hero.as and Female.as:
[Embed(source="../assets/FireBoy.jpg")]
private static const HeroFireBoy:Class;
in your Hero.as and Female.as, to assign the correct image.

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

ADDED_TO_STAGE Event doesn't work in certain frame?

This is Heli's Class and it'll called in main class ,the target of main class in frame 2 .
The frame 1 contain button that can make me go to frame 2 .but this movie clip of Heli doesn't added to the stage . but it'll work if i targeting main class in frame 1 . so can anyone tell me how to use added_to_stage event in specified frame ??? (sorry about my english)
package com.ply
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Heli extends MovieClip
{
//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;
private var bullets:Array;
private var missiles:Array;
public function Heli()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
private function init():void
{
stage.addEventListener(Event.ENTER_FRAME, runGame);
}
private function runGame(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 Heli()
{
if (stage) init();
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
here it 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.events.Event;
import flash.events.MouseEvent;
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();
//================================================
public function Main()
{
//stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// instantiate car class
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 {
//addChild(bulletholder);
addChild(bulletContainer);
gameState = STATE_START_PLAYER;
gameLoop();
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add car to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
//CheckTime();
gameLoop();
//txtScore.text = 'Score: '+score;
}
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
player.xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
player.yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 1;
}
else if (event.keyCode == 32 && shootAllow)
{
fireBullet();
}
}
public function fireBullet() {
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
var newBullet2:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = player.x+20; //+ player.width/2 - player.width/2;
newBullet.y = player.y;
newBullet2.x = player.x-20;
newBullet2.y = player.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
bulletContainer.addChild(newBullet2);
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
//if time hasn't reached the limit, then just increment
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;
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 0;
}
}
}
}