how to make object move in specific position flash as3 - actionscript-3

I make an mc object. this object can move right and left with keyboard. details are when I push rightkey it moves to right position in certain coordinate and when I push leftkey it moves to left position in certain coordinate. I want the object just move in 3 position.
for this case, I tried to use array.
var P:Array = [new Point(100, 300), new Point(275, 300), new Point(425, 300)];
var M:Array = [Kotak];
but when I input them to my code, it doesn't work and no error appears. anyone can tell me where's my fault?
this's my full code :
import flash.geom.Point;
//gerak pemain
var pemainKanan:Boolean = false;
var pemainTengah:Boolean = false;
var pemainKiri:Boolean = false;
//kecepatan
var kecepatanPemain:int = 20;
//Array object acak
var P:Array = [new Point(100, 300), new Point(275, 300), new Point(425, 300)];
var M:Array = [Kotak];
//var P:Point = new Point(100, 300);
Kotak.addEventListener(KeyboardEvent.KEY_UP, k);
function k(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.RIGHT){
pemainKanan = false;
}
if(e.keyCode == Keyboard.LEFT){
pemainKiri = false;
}
}
Kotak.addEventListener(KeyboardEvent.KEY_DOWN, kk);
function kk(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.RIGHT){
pemainKanan = true;
}
if(e.keyCode == Keyboard.LEFT){
pemainKiri = true;
}
}
Kotak.addEventListener(Event.ENTER_FRAME, eframe);
function eframe(e:Event):void{
if(pemainKanan == true){
//pemain.gotoAndStop("right");
Kotak.x = P[0];
}
else if(pemainKiri == true){
//pemain.gotoAndStop("left");
Kotak = P[1];
}
}

Can you please explain that in detail? From what I've read I understand that you want a MovieClip to move to three positions. For example if it is on position0 and right is pressed it should move to position1, but if it's in position1 it should move to position2 and the other way around with left button. Is this what you want to do? If it is there is no need for the ENTER_FRAME event, since all it can be done maybe with an index.
Kotak.addEventListener(KeyboardEvent.KEY_DOWN, kk);
var index:int=0;
function kk(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.RIGHT){
if(index==0){
Kotak.x = P[1];
}
else{
if(index==1){
Kotak.x = P[2];
}
}
index++;
}
if(e.keyCode == Keyboard.LEFT){
if(index==2){
Kotak.x = P[1];
}
else{
if(index==1){
Kotak.x = P[0];
}
}
index--;
}
}

Related

AS3 Restrict ship in visible stage area

Hey so i've been making a space shooter game and i created the movement but i'm trying to restricting the ship to the visible stage area and i can't figure out how to do that
also i'm sorry if my code it's really messy i'm really new at this
the stage size it's 1920 x 1080
here's the code of the movement
var leftKeyPressed: Boolean = false;
var rightKeyPressed: Boolean = false;
var upKeyPressed: Boolean = false;
var downKeyPressed: Boolean = false;
var xMoveSpeed: Number = 15;
var yMoveSpeed: Number = 15;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyDownHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT)
{
leftKeyPressed = true;
}
if (e.keyCode == Keyboard.RIGHT)
{
rightKeyPressed = true;
}
if (e.keyCode == Keyboard.UP)
{
upKeyPressed = true;
}
if (e.keyCode == Keyboard.DOWN)
{
downKeyPressed = true;
}
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
function keyUpHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT)
{
leftKeyPressed = false;
}
if (e.keyCode == Keyboard.RIGHT)
{
rightKeyPressed = false;
}
if (e.keyCode == Keyboard.UP)
{
upKeyPressed = false;
}
if (e.keyCode == Keyboard.DOWN)
{
downKeyPressed = false;
}
}
stage.addEventListener(Event.ENTER_FRAME, moveHero);
function moveHero(e: Event): void
{
if (leftKeyPressed)
{
ship.x -= xMoveSpeed;
}
if (rightKeyPressed)
{
ship.x += xMoveSpeed;
}
if (upKeyPressed)
{
ship.y -= yMoveSpeed;
}
if (downKeyPressed)
{
ship.y += yMoveSpeed;
}
}
Well, you can start with this.
// One map is much better than a separate variable for each and every key.
var keyMap:Object = new Object;
// Initial keymap values.
keyMap[Keyboard.UP] = 0;
keyMap[Keyboard.DOWN] = 0;
keyMap[Keyboard.LEFT] = 0;
keyMap[Keyboard.RIGHT] = 0;
// With the keymap you don't need these big event handlers,
// you need a single one with one line of code.
stage.addEventListener(KeyboardEvent.KEY_DOWN, onUpDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUpDown);
function onUpDown(e:KeyboardEvent):void
{
// The members of the object with the names of key codes
// will be set to 1 in case of KEY_DOWN event or 0 in case of KEY_UP.
keyMap[e.keyCode] = int(e.type == KeyboardEvent.KEY_DOWN);
}
stage.addEventListener(Event.ENTER_FRAME, moveHero);
// This will provide you with min and max values for both X and Y coordinates.
// You will probably need to adjust it because the ship have width and height.
var conStraints:Rectangle = new Rectangle(0, 0, 1920, 1080);
var xMoveSpeed:Number = 15;
var yMoveSpeed:Number = 15;
function moveHero(e:Event):void
{
var anX:Number = ship.x;
var anY:Number = ship.y;
// Use keymap to figure the new coordinates.
// Take into account all the relevant keys pressed.
anX += xMoveSpeed * (keyMap[Keyboard.RIGHT] - keyMap[Keyboard.LEFT]);
anY += yMoveSpeed * (keyMap[Keyboard.DOWN] - keyMap[Keyboard.UP]);
// Now set the new ship coordinates with the regard to constraints.
ship.x = Math.min(conStraints.right, Math.max(conStraints.left, anX));
ship.y = Math.min(conStraints.bottom, Math.max(conStraints.top, anY));
}
I think this is the easiet solution, tell me if it worked or not
function keyDownHandler(e: KeyboardEvent): void
{
if (e.keyCode == Keyboard.LEFT && ship.x > 15)
{
leftKeyPressed = true;
}
if (e.keyCode == Keyboard.RIGHT && ship.x < 1905)
{
rightKeyPressed = true;
}
if (e.keyCode == Keyboard.UP && ship.y > 15)
{
upKeyPressed = true;
}
if (e.keyCode == Keyboard.DOWN && ship.y < 1065)
{
downKeyPressed = true;
}
}

as3 error: ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value

I am following a tutorial on building a rhythm game in as3 here, and I am very new to the language. On running the swf, I get the following error in the output:
ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value.
at source_fla::MainTimeline/makeLvl()[source_fla.MainTimeline::frame10:116]
I have tried some previous solutions posted to the same error, but I have not been able to resolve the issue.
Here is the source code:
stop();
stage.focus = stage;
//VARIABLES
//sTime is the current frame that is being played
//Once it reaches sTempo, then it will be reset
//and a note will be created
var sTime:int = 0;
//sTempo is how many frames it takes before
//a note is created. Because it's 12, and
//the frame rate is 24, it will take a half of a second
//for a note to be made
var sTempo:Number = 12;
//sNote is the current arrow of the level that is created
//0 makes no arrow
//1 makes a left arrow
//2 makes an up arrow
//3 makes a down arrow
//4 makes a right arrow
var sArrow:int = 0;
//arrowSpeed is how fast the arrow moves up the screen
var arrowSpeed:Number = 10;
//gameIsOver is whether the game's over
var gameIsOver:Boolean = false;
//the score variable
var score:int = 0;
//either perfect, great, nice, or good
var scoreString:String = '';
var combo:int = 0;
var mcHealth:Number = 0;
//Booleans checking if the arrows are touching the receptor
var touchLeft:Boolean = false;
var touchUp:Boolean = false;
var touchDown:Boolean = false;
var touchRight:Boolean = false;
function beginCode():void{
addEventListener(Event.ENTER_FRAME, makeLvl);
//make the level array longer
lvlArrayAll[lvlCurrent].push(0,0,0,0,0);
}
function makeLvl(e:Event):void{
//code here will create the level
if(sTime < sTempo){
//if the required time hasn't reached the limit
//then update the time
sTime ++;
} else {
//if the time has reached the limit
//then reset the time
sTime = 0;
//if an actual arrow can be made
if(lvlArrayAll[lvlCurrent][sArrow] != 0){
var currentArrow:MovieClip; //this will hold the current arrow
if(lvlArrayAll[lvlCurrent][sArrow] == 1){
//place a left note onto the stage
currentArrow = new arrowLeft();
//set the _x value of the note so that it is in the
//right place to touch the receptor
currentArrow.x = 105 ;
//set the note's y coordinate off of the stage
//so that the user can't see it when it appears
currentArrow.y = 0;
//setting the key that needs to be pressed
currentArrow.keyCode = 68;
addChild(currentArrow);//add it to stage
} else if(lvlArrayAll[lvlCurrent][sArrow] == 2){
//place an up note onto the stage
currentArrow = new arrowUp();
currentArrow.x = 230;
currentArrow.y = 0;
currentArrow.keyCode = 70;
addChild(currentArrow);
} else if(lvlArrayAll[lvlCurrent][sArrow] == 3){
//place a down note onto the stage
currentArrow = new arrowDown();
currentArrow.x = 355;
currentArrow.y = 0;
currentArrow.keyCode = 74;
addChild(currentArrow);
} else if(lvlArrayAll[lvlCurrent][sArrow] == 4){
//place a right note onto the stage
currentArrow = new arrowRight();
currentArrow.x = 480;
currentArrow.y = 0;
currentArrow.keyCode = 75;
addChild(currentArrow);
}
}
//get the next arrow if it the song isn't finished
if(sArrow < lvlArrayAll[lvlCurrent].length){
sArrow ++;
} else {
//if the song is finished, then reset the game
gotoAndStop('win');
gameIsOver = true;
//then remove this enter_frame listener
removeEventListener(Event.ENTER_FRAME, makeLvl);
}
}
//checking if mcReceptor is touching any arrows
//first we reset the variables we got last time just in case they aren't true anymore
touchLeft = false;
touchUp = false;
touchDown = false;
touchRight = false;
//this for loop will be used for the hit testing
for(var i:int = 0;i<numChildren;i++){
var target:Object = getChildAt(i);
if(target.keyCode != null && target.hitTestObject(mcReceptor)){//if the object is an arrow and the receptor is touching it
if(target.keyCode == 68){//if left arrow
touchLeft = true;
} else if(target.keyCode == 70){//if up arrow
touchUp = true;
} else if(target.keyCode == 74){//if down arrow
touchDown = true;
} else if(target.keyCode == 75){//if right arrow
touchRight = true;
}
}
}
//changing the score text
mcTxt.txtScore.text = 'Score: '+score;
mcTxt.txtCombo.text = 'Combo: '+combo;
mcTxt.txtScoreString.text = scoreString;
}
//this function will change the health depending on how much health change
//it needs, positive or negative
function changeHealth(healthDiff:Number):void{
healthDiff = 100;//only changes in percentages
//checking if the health is already at it's full
//or will be full after this hit
if(mcHealth + healthDiff >= 100){
mcHealth = 100;
} else if(mcHealth + healthDiff <= 0){
//checking if the health will be equal or below 0
gotoAndStop('lose');
gameIsOver = true;
removeEventListener(Event.ENTER_FRAME, makeLvl);
} else {
//if there are no problems
mcHealth += healthDiff;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeys);
function checkKeys(event:KeyboardEvent):void{
//if the left key is down and no left arrows are touching the receptor
if(event.keyCode == 68 && !touchLeft){
changeHealth(-10);//make the health go down
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 70 && !touchUp){//and so on
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 74 && !touchDown){
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 75 && !touchRight){
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
}
}
beginCode();
Can someone tell me why this error is occurring? Thank you.
While iterating numChildren, it's necessary to check the object is an arrow or not.
Maybe you can distinguish it by having keyCode property or not.
Try to use Object.hasOwnProperty(property name) method.
if (target.hasOwnProperty("keyCode")){
// access target.keyCode here.
}
Or this might works too.
if (target is arrowLeft || target is arrowUp || target is arrowDown || target is arrowRight){
// the target should be arrow class
// access target.keyCode here.
}
//this for loop will be used for the hit testing
for(var i:int = 0;i<numChildren;i++){
var target:Object = getChildAt(i);
if (target.hasOwnProperty("keyCode")){ // If the object is an arrow, that object should has keyCode property.
if(target.keyCode != null && target.hitTestObject(mcReceptor)){//if the object is an arrow and the receptor is touching it
if(target.keyCode == 68){//if left arrow
touchLeft = true;
} else if(target.keyCode == 70){//if up arrow
touchUp = true;
} else if(target.keyCode == 74){//if down arrow
touchDown = true;
} else if(target.keyCode == 75){//if right arrow
touchRight = true;
}
}
}
}

Flash Collision Detection (Platformer game)

I am trying to make a platformer game in flash, using ActionScript 3. Currently everything is working except for one thing.
The Problem:
When the player collides with the bottom of a platform, if his xVel is not equal to zero, the horizontal collision detection loop is called and the player is moved horizontally as well as vertically. This means he bounces off the platform from underneath but is also displaced to one side of the platform. If the player's xVel is equal to zero, everything works fine. This is because the horizontal collision loop is not called. I cannot figure out why this happens. Any help would be greatly appreciated.
The Code:
import flash.events.Event;
import flash.geom.Rectangle;
var level:Array = new Array();
var xVel = 0;
var yVel = 0;
var xSpeed = 15;
var accel =1.5;
var grav = 2;
var jumpHeight = 15*grav;
for(var i = 0; i<numChildren;i++){
if(getChildAt(i) is platform){
level.push(getChildAt(i).getRect(this));
}
}
var upKeyDown = false;
var leftKeyDown = false;
var rightKeyDown = false;
var downKeyDown = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUp);
stage.addEventListener(Event.ENTER_FRAME,gameLoop);
function keyDown(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
upKeyDown = true;
}
if(e.keyCode == Keyboard.LEFT){
leftKeyDown = true;
}
if(e.keyCode == Keyboard.RIGHT){
rightKeyDown = true;
}
if(e.keyCode == Keyboard.DOWN){
downKeyDown = true;
}
}
function keyUp(e:KeyboardEvent){
if(e.keyCode == Keyboard.UP){
upKeyDown = false;
}
if(e.keyCode == Keyboard.LEFT){
leftKeyDown = false;
}
if(e.keyCode == Keyboard.RIGHT){
rightKeyDown = false;
}
if(e.keyCode == Keyboard.DOWN){
downKeyDown = false;
}
}
function gameLoop(e:Event){
if(rightKeyDown){
if(xVel<xSpeed){
xVel+=accel;
}
}else if(leftKeyDown){
if(xVel>-xSpeed){
xVel-=accel;
}
}else{
xVel *=0.6;
}
//horizontal
player.x+=xVel;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(xVel>0){
player.x = level[i].left-player.width/2;
}
if(xVel<0){
player.x = level[i].right+player.width/2;
}
xVel = 0;
}
}
yVel+=grav;
player.y+=yVel;
var jumpable = false;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(yVel>0){
player.y = level[i].top-player.height/2;
yVel = 0;
jumpable = true;
}
if(yVel<0){
player.y = level[i].bottom+player.height/2;
yVel*=-0.5;
}
}
}
if(upKeyDown&&jumpable){
jump();
}
this.x = -player.x+(stage.stageWidth/2);
this.y = -player.y+(stage.stageHeight/2);
}
function jump(){
yVel-=jumpHeight;
}
Where I think the problem occurs
player.x+=xVel;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(xVel>0){
player.x = level[i].left-player.width/2;
}
if(xVel<0){
player.x = level[i].right+player.width/2;
}
xVel = 0;
}
}
yVel+=grav;
player.y+=yVel;
var jumpable = false;
for(i = 0; i<level.length;i++){
if(player.getRect(this).intersects(level[i])){
if(yVel>0){
player.y = level[i].top-player.height/2;
yVel = 0;
jumpable = true;
}
if(yVel<0){
player.y = level[i].bottom+player.height/2;
yVel*=-0.5;
}
}
}
The picture!
Extra information:
The platforms are movie clip symbols, all originating from the same symbol. They are dragged onto the canvas and re sized. The platform symbol has an AS linkage called 'platform' which is how the child is identified as a platform in the code
The player is a rectangle with no animations
Both the platforms and player have an orientation in the center of the object.
What you need to to is test the ceiling collision first and adjust accordingly before the horizontal check. If you don't, then you player is colliding with the bottom of the platform when you do the horizontal check.

How Do I spawn Enemy at either the far left or the far right of the stage and have them move in to the center?

First I get This Error
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Game_fla::MainTimeline/testCollisions()[Game_fla.MainTimeline::frame1:205]
and here is my code
// ******* IMPORTS *****
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
//*****VARIABLES****
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var shootDown:Boolean = false;
var ySpeed:int = 0;
var xSpeed:int = 0;
var scrollX:int = 0;
var scrollY:int = 0;
var speedConstant:int = 5;
var friction:Number = 0.6;
var level:Number = 1;
var bullets:Array = new Array();
var container_mc:MovieClip;
var enemies:Array;
var tempEnemy:MovieClip;
// BUTTON EVENTS EITHER CLICKED OR NOT
left_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveLeft);
right_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveRight);
up_btn.addEventListener(MouseEvent.MOUSE_DOWN, moveUp);
shoot_btn.addEventListener(MouseEvent.MOUSE_DOWN, shootPressed);
left_btn.addEventListener(MouseEvent.MOUSE_UP, leftUp);
right_btn.addEventListener(MouseEvent.MOUSE_UP, rightUp);
up_btn.addEventListener(MouseEvent.MOUSE_UP, upUp);
stage.addEventListener(Event.ENTER_FRAME, makeEnemies);
player.gotoAndStop('still');
stage.addEventListener(Event.ENTER_FRAME,onenter);
function onenter(e:Event):void{
if (rightPressed == true && leftPressed == false){
player.x += 8;
player.scaleX = 1;
player.gotoAndStop("walking");
cloud.x -= 8;
} else if (leftPressed == true && rightPressed == false){
player.x -= 8;
player.scaleX = -1;
player.gotoAndStop('walking');
cloud.x += 8;
} else if(upPressed == true && leftPressed == false && rightPressed == false){
}
else{
rightPressed = false;
leftPressed = false;
player.gotoAndStop('still')}
}
// **** MOVEMENT CONTROLS *********
function shootPressed(e:MouseEvent):void{
shootDown = true;
if(shootDown == true){
fireBullet();
}
}
function fireBullet():void
{
var playerDirection:String;
if(player.scaleX < 0){
playerDirection = "left";
} else if(player.scaleX > 0){
playerDirection = "right";
}
var bullet:Bullet = new Bullet(player.x, player.y, playerDirection);
//bullets = new Array();
bullet.y = player.y + 8;
stage.addChild(bullet);
bullets.push(bullet);
trace(bullets);
}
// BUTTON FUNCTIONS
function moveLeft(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
leftPressed = true;
}else if (MouseEvent.MOUSE_UP) {
leftPressed = false;
}
}
function moveRight(e:MouseEvent):void
{
if (MouseEvent.MOUSE_DOWN){
rightPressed = true;
}else if (MouseEvent.MOUSE_UP){
rightPressed = false;
}
}
function moveUp(e:MouseEvent):void
{
if(MouseEvent.MOUSE_DOWN){
upPressed = true;
} else if (MouseEvent.MOUSE_UP) {
upPressed = false;
}
}
function leftUp(e:MouseEvent):void
{
leftPressed = false;
}
function rightUp(e:MouseEvent):void
{
rightPressed = false;
}
function upUp(e:MouseEvent):void
{
upPressed = false;
}
enemies = new Array();
//Call this function for how many enemies you want to make...
function makeEnemies(e:Event):void
{
var chance:Number = Math.floor(Math.random() * 60);
if (chance <= 2){
//Make sure a Library item linkage is set to Enemy...
tempEnemy = new enemy();
tempEnemy.speed = 80;
tempEnemy.x = Math.round(Math.random() * stage.stageWidth) * -10;
addChild(tempEnemy);
enemies.push(tempEnemy);
moveEnemies();
}
}
function moveEnemies():void
{
var tempEnemy:MovieClip;
for (var i:int =enemies.length-1; i>=0; i--)
{
tempEnemy = enemies[i];
tempEnemy.x += tempEnemy.speed;
tempEnemy.y = 285;
}
}
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
//Check for collisions between an enemies array and a Lasers array
function testCollisions(e:Event):void
{
var tempEnemy:MovieClip;
var tempLaser:MovieClip;
for (var i:int=enemies.length-1; i >= 0; i--)
{
tempEnemy = enemies[i];
for (var j:int=bullets.length-1; j>=0; j--)
{
tempLaser = bullets[j];
if (tempLaser.hitTestObject(tempEnemy))
{
removeChild(tempEnemy);
removeChild(tempLaser);
trace("BULLET HIT");
stage.addEventListener(Event.ENTER_FRAME, testCollisions);
}
}
}
}
I Understand that I need to reference the parent whenever I removeChild in the testCollision function but I dont know where.
Also I want the zombies to spawn out of the stage and move in towards the center at a smooth speed with the code I have they just seem to spawn sort of rearly and always to the left of the stage. So I would need to spawn them off the stage and have them move in to the center and change their ScaleX position to change their dirention but I dont know how to do that Please help.
I think you can fix the error you listed by changing removeChild(tempLaser) to stage.removeChild(tempLaser) since the stage is where you added your bullets, so that's where you need to remove them from.
I'll give you a hint on the zombie movement, but you'll probably want to find a programming forum/friend/professor to help with general code design questions like this. In moveEnemies, you'll need to decide whether the zombie should move left/right (based on whether their x position is larger or smaller than the player's), and whether they should move up/down (based on whether their y position is larger or smaller than the player's).
For example, if their x position is larger than the player's, you would do tempEnemy.x -= tempEnemy.speed, and if smaller, you would do tempEnemy.x += tempEnemy.speed. But as I said, this site isn't really made for these types of design questions.

How to make object reset my game?

I am a student working on a project with flash. I am simply trying to make a flash game using Actionscript 3 in Adobe Flash CS5. Everything is working fine, i can walk and jump, but I want the game to restart if the Main character touches an object and dies (like spikes in a pit). I have a main menu in frame 1 and the first level on frame 2. The main character is called "player_mc" and the object that kills him is called "dies". Help and tips is very much appreciated.
Code:
//The Code For The Character (Player_mc)
import flash.events.KeyboardEvent;
import flash.events.Event;
var KeyThatIsPressed:uint;
var rightKeyIsDown:Boolean = false;
var leftKeyIsDown:Boolean = false;
var upKeyIsDown:Boolean = false;
var downKeyIsDown:Boolean = false;
var playerSpeed:Number = 20;
var gravity:Number = 1;
var yVelocity:Number = 0;
var canJump:Boolean = false;
var canDoubleJump:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, PressAKey);
stage.addEventListener(KeyboardEvent.KEY_UP, ReleaseAKey);
//This two functions cllapsed is the keybindings that the game uses
function PressAKey(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.D)
{
rightKeyIsDown = true;
}
if(event.keyCode == Keyboard.A)
{
leftKeyIsDown = true;
}
if(event.keyCode == Keyboard.SPACE)
{
upKeyIsDown = true;
}
if(event.keyCode == Keyboard.S)
{
downKeyIsDown = true;
}
}
function ReleaseAKey(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.D)
{
rightKeyIsDown = false;
}
if(event.keyCode == Keyboard.A)
{
leftKeyIsDown = false;
}
if(event.keyCode == Keyboard.SPACE)
{
upKeyIsDown = false;
}
if(event.keyCode == Keyboard.S)
{
downKeyIsDown = false;
}
}
//Player animations
player_mc.addEventListener(Event.ENTER_FRAME, moveThePlayer);
function moveThePlayer(event:Event):void
{
if(!canJump || rightKeyIsDown && !canJump || leftKeyIsDown && !canJump)
{
player_mc.gotoAndStop(3);
}
if(!upKeyIsDown && !rightKeyIsDown && !leftKeyIsDown && canJump)
{
player_mc.gotoAndStop(1);
}
if(rightKeyIsDown && canJump || leftKeyIsDown && canJump)
{
player_mc.gotoAndStop(2);
}
//Animation stops here
if(rightKeyIsDown)
{
floor_mc.x -= playerSpeed;
dies.x -= playerSpeed;
player_mc.scaleX = 0.3;
}
if(leftKeyIsDown)
{
floor_mc.x += playerSpeed;
dies.x += playerSpeed;
player_mc.scaleX = -0.3;
}
if(upKeyIsDown && canJump)
{
yVelocity = -18;
canJump = false;
canDoubleJump = true;
}
if(upKeyIsDown && canDoubleJump && yVelocity > -2)
{
yVelocity =-13;
canDoubleJump = false;
}
if(!rightKeyIsDown && !leftKeyIsDown && !upKeyIsDown)
{
player_mc.gotoAndStop(1);
}
yVelocity +=gravity
if(! floor_mc.hitTestPoint(player_mc.x, player_mc.y, true))
{
player_mc.y+=yVelocity;
}
if(yVelocity > 20)
{
yVelocity =20;
}
for (var i:int = 0; i<10; i++)
{
if(floor_mc.hitTestPoint(player_mc.x, player_mc.y, true))
{
player_mc.y--;
yVelocity = 0;
canJump = true;
}
}
}
If I understand this right, when you die, you want to restart the level. To do this, you could save all your initial variables like player position, floor position, etc in an array, then on death, restore those variables to their corresponding object. However, when you get more complex and have lots and lots of objects, it could become tricky.
A simpler solution is to display a death screen of some sorts on another frame (lets call it frame 3) when you hit the dies object, and on that death screen when you press a restart button or after a certain time delay, it then goes back to frame 2 and restarts the level.
Example:
Put this in your moveThePlayer function:
if(dies.hitTestPoint(player_mc.x, player_mc.y, true))
{
// remove all the event listeners
player_mc.removeEventListener(Event.ENTER_FRAME, moveThePlayer);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, PressAKey);
stage.removeEventListener(KeyboardEvent.KEY_UP, ReleaseAKey);
gotoAndStop(3); // this has your "dead" screen on it.
}
And on frame 3, have something like:
import flash.events.MouseEvent;
retry_button.addEventListener(MouseEvent.CLICK, retry);
function retry(e:MouseEvent) {
retry_button.removeEventListener(MouseEvent.CLICK, retry);
// back to the level
gotoAndStop(2);
}
You could also do something like storing a variable on which frame you want to go back to, so you have a single retry frame which can go to whatever level you were just on.
A good habit that you should develop is having an endGame() or similar method that you update as you work on the game.
For example:
function endGame():void
{
// nothing here yet
}
Now lets say you create a player. The player is initially set up like this:
player.health = 100;
player.dead = false;
You'll want to update your endGame() method to reflect this.
function endGame():void
{
player.health = 100;
player.dead = false;
}
Got some variables related to the game engine itself?
var score:int = 0;
var lives:int = 3;
Add those too:
function endGame():void
{
player.health = 100;
player.dead = false;
score = 0;
lives = 3;
}
Now endGame() should reset the game back to its original state. It's much easier to work this way (as you code the game) rather than leaving it until last and trying to make sure you cover everything off, which is unlikely.