Level progression in a platform game? (Actionscript 3) - actionscript-3

I've been working on a Platformer for a couple of weeks now and i can't seem to get the level progression working. I'm using a basic hitTest on a box to signal the movement from frame 1(level 1) to frame 2 (level 2) but once the character hits the exit box, i get the following error
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at LevelProg_fla::MainTimeline/loop()
What can i do so that it moves to the next frame(level)? If it helps, my code is in a frame rather than a class. Basically, the only code that i'm using for level progression is
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
with "levelTwo" being the name of the next frame (next level). The rest of the game's code is as follows (pardon the messyness of it, I've been more focused on getting the darn thing to work :b)
import flash.events.KeyboardEvent;
import flash.events.Event;
//some variables to track the player's speed
var speedX = 0;
var speedY = 0;
player.height = 80.0;
player.width = 60.0;
//loop through all the platform objects to generate the level
var level:Array = new Array();
for (var i=0; i<numChildren; i++)
{
if (getChildAt(i) is platform)
{
level.push(getChildAt(i).getRect(this));
}
}
//make variables to store key states
var kUp = false;
var kDown = false;
var kLeft = false;
var kRight = false;
//listen for key presses and releases
stage.addEventListener(KeyboardEvent.KEY_DOWN, kD);
stage.addEventListener(KeyboardEvent.KEY_UP, kU);
function kD(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=true;
if (k.keyCode==38) kUp=true;
if (k.keyCode==39) kRight=true;
if (k.keyCode==40) kDown=true;
}
function kU(k:KeyboardEvent)
{
if (k.keyCode==37) kLeft=false;
if (k.keyCode==38) kUp=false;
if (k.keyCode==39) kRight=false;
if (k.keyCode==40) kDown=false;
}
//Make a looping function
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
//lateral movement checks
if (kLeft)
{
speedX=-10;
}
else if (kRight)
{
speedX=10;
}
else
{
speedX*=0.5; //friction to slow player down (kinda like mario)
}
//does not stop the character
//move player based on the above
player.x+=speedX;
//animations
if (speedX > 0)
{
trace("right pressed");
//player.gotoAndPlay("walkRight");
}
if (speedX < 0)
{
trace("left pressed");
//player.gotoAndPlay("walkLeft");
}
//sidewards hit tests
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedX > 0) ////moving right collision and stuffs
{
player.x = level[i].left-player.width/2;
}
if (speedX < 0) ////moving left collision and stuffs
{
player.x = level[i].right+player.width/2;
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//vertical checks
speedY+=1;
player.y+=speedY;
var jumpable = false
//vertical hitTests
//note that it's the same as the x code but just changed like 5 things.
for (i=0; i<level.length; i++)
{
if (player.getRect(this).intersects(level[i]))
{
if (speedY > 0) ////moving down collision and stuffs
{
player.y = level[i].top-player.height/2;
speedY=0;
jumpable = true;
}
if (speedY < 0) ////moving up collision and stuffs
{
player.y = level[i].bottom+player.height/2;
speedY*=-0.5; //bounces off cielings
}
//RIGHTIO
speedX = 0 //kills the speed
}
}
//jumps if possible
if (kUp && jumpable)
{
speedY=-15;
}
//gravity might help}
//move player with camera function/code/script/tired
this.x=-player.x+(stage.stageWidth/2); //centers the player
this.y=-player.y+(stage.stageWidth/2); //centers the player
//Progresses the player to level 2
if (player.hitTestObject(exit))
{
gotoAndPlay("levelTwo");
}
}

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

Flash as3 Pivoting an object round a point

In Flash cc, I am wondering how I can make a drag and drop game. But depending on were you drag the object will rotate so gravity will effect it. For instance if you pick up a a piece of paper with your thumb and index at the bottom the paper will rotate so you are holding it at the top. How can I recreate this in flash???
Here is my code so far... (I am a big newbie to flash so please be generous with answers)
var drag:Number = 1;
var BlockAppear = new MovieClip;
gotoAndStop(1, "Minigame-Block");
HeartBear.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_4);
function fl_ClickToDrag_4(event:MouseEvent):void
{
HeartBear.startDrag()
gravity = 0
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_4);
function fl_ReleaseToDrop_4(event:MouseEvent):void
{
HeartBear.stopDrag();
gravity = 0.9
}
{
var gravity = 0.9;
var floor = 241.3;
HeartBear.y = 710.9;
HeartBear.speedY = 0;
HeartBear.impulsion = 10;
stage.addEventListener(Event.ENTER_FRAME, enterframe);
function enterframe(e:Event) {
HeartBear.speedY += gravity;
HeartBear.y += HeartBear.speedY;
if(HeartBear.y > floor) {
HeartBear.speedY = 0;
HeartBear.y = floor
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, space);
function space(e:KeyboardEvent) {
if(e.keyCode == Keyboard.SPACE) {
HeartBear.speedY = -HeartBear.impulsion
}
}
}
Shopclicker.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_3);
function fl_ClickToGoToScene_3(event:MouseEvent):void
{
MovieClip(this.root).gotoAndStop(1, "Shop");
}

Flash As3 Variable Issue

I have a variable on frame 1 that starts at 3000 and keeps decreasing. This variable determines the gap of time between the spawn of an object. so basically the objects spawn quicker and quicker as the this number decreases. Everything works fine except the fact when i make the character die and the main timeline goes to frame 2 to show the death screen. When clicked "play again" on that frame that makes you come back to frame 1. the objects keep spawning at whatever speed they were spawning before death. Even though the variable resets to 3000 when "play again" clicked..
I traced the variable and it does truely reset. but for some reason those spawning objects follow the previous variable.
Heres the code on the first Frame:
import flash.events.Event;
stop();
var num1:Number = 0;
var scrollSpeed:Number = 3000;
var playerState:Number = 1;
var alive:Boolean = true;
var Redbars:Array = new Array();
var Bluebars:Array = new Array();
var scoreCount:Number = 10;
addEventListener(Event.ENTER_FRAME, update);
function update(e:Event){
trace(scrollSpeed);
scoreCount += 1;
scoreText.text = (scoreCount).toString();
//SCROLL SPEED-------------------
if(scrollSpeed > 300)
{
scrollSpeed -= 1;
}
//--------------------------------
CheckForCollisionBlue();
CheckForCollisionRed();
//trace(alive);
if(player.currentFrame == 1){
playerState = 1;
}
//Check if lost
if(player.hitTestObject(leftHitBox)){
gotoAndStop(2);
scoreEnd.text = (scoreCount).toString();
}
//If dead Delete Object
if(currentFrame == 2){
deleteBlue();
deleteRed();
}
}
////
//Timer////////////////////////////////
var myTimer:Timer = new Timer(scrollSpeed,10000000);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
//Generate Random number
num1 = randomRange();
trace(num1);
//IF NUM1 = 1------------------------------------------
if(num1 == 1){
//Create a Red Bar
var redBar = new Jump_Cube();
Redbars.push(redBar); //add enemy to the array
redBar.x = -33;
redBar.y = 99;
redBar.width = 12.5;
redBar.height = 20.45;
//Update the Bar
for(var i:int=0; i < Redbars.length; i++){
if(currentFrame == 1)
{
addChild(Redbars[i]);
}
}
}
//IF NUM1 = 2------------------------------------------
if(num1 == 2){
//Create a Blue Bar
var blueBar = new Jump_Cube2();
Bluebars.push(blueBar); //add enemy to the array
blueBar.x = -26.8;
blueBar.y = 10;
blueBar.width = 12.25;
blueBar.height = 31.90;
//Update the Bar
for(var j:int=0; j < Bluebars.length; j++){
if(currentFrame == 1)
{
addChild(Bluebars[j]);
}
}
myTimer.delay = scrollSpeed;
}
}
myTimer.start();
//--------------------------------------------------------------------
//Check for Collision------------------------------
function CheckForCollisionBlue(){
for(var i:int=0; i < Bluebars.length; i++){
if( player.hitTestObject(Bluebars[i]) ){
//Collision
trace("Didnt Hit Blue");
player.x -= 5;
player.y += 1;
}
}
}
//Check for Collision------------------------------
function CheckForCollisionRed(){
for(var i:int=0; i < Redbars.length; i++){
if( player.hitTestObject(Redbars[i]) ){
//Collision
trace("Didnt Hit Red");
player.x -= 5;
player.y += 1;
}
}
}
function randomRange():Number
{
return (Math.floor(Math.random() * (2 - 1 + 1)) + 1);
}
///////////BUTTONS------------------
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
redButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndRed);
function onTouchEndRed(e:TouchEvent):void{
player.gotoAndPlay(2);
playerState = 2;
}
blueButton.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchEndBlue);
function onTouchEndBlue(e:TouchEvent):void{
player.gotoAndPlay(19);
playerState = 3;
}
///////--CLEARING STAGE
//--------------------------------------------------------------------
//delete Blue------------------------------
function deleteBlue(){
for(var i:int=0; i < Bluebars.length; i++){
removeChild(Bluebars[i]);
}
}
//delete Red------------------------------
function deleteRed(){
for(var i:int=0; i < Redbars.length; i++){
removeChild(Redbars[i]);
}
}
Heres the code on the second frame:
stop();
alive = false;
againButton.addEventListener(TouchEvent.TOUCH_END, again);
function again(e:TouchEvent):void{
gotoAndStop(1);
playerState = 1;
scrollSpeed = 3000;
deleteBlue();
deleteRed();
}
You have to put in a removeEventListener(Event.ENTER_FRAME, update); inside your onTouchEndRed function. And probably also inside of this 'if' conditional: if(player.hitTestObject(leftHitBox)){...
Simply stop programming using frames. Use classes instead. AS3 is based on classes. It'll take you a lot of benefits. This link may help you to start: http://www.adobe.com/devnet/actionscript/getting_started.html
Additionally, FlashPlayer executes frame's code each time you jump to another frame. Thats why your variables are reinitializing.

Objects to bounce around the screen?

I would like to make the 5 'burger' objects bounce around the screen so they are harder to shoot as is the aim of my game. But, so far they are only lining up at the top of the stage so it's way too easy to play. Would I need to create 5 separate objects with 5 separate instance names etc.
This is what I have so far:
var firing:Boolean = false;
var bullet:Bullet1 = new Bullet1();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function keydown(event:KeyboardEvent):void {
switch(event.keyCode) {
case Keyboard.LEFT :
ball.x -= 10;
break;
case Keyboard.SPACE :
if (!firing) {
fire();
}
break;
case Keyboard.RIGHT :
ball.x += 10;
break;
case Keyboard.UP :
ball.y -= 10;
break;
case Keyboard.DOWN :
ball.y += 10;
break;
default :
break;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
function fire() {
addChild(bullet);
firing = true;
bullet.x = ball.x;
bullet.y = ball.y - 60
;
}
addEventListener(Event.ENTER_FRAME, movestuff);
function movestuff(event:Event):void {
if (firing) {
bullet.y -= 20;
if (bullet.y < 0) {
firing = false;
removeChild(bullet);
}
}
}
var numBurger:Number = 5;
var array:Array = new Array();
for (var i:uint = 0; i<numBurger; i++) {
var burger:Burger = new Burger();
array.push(burger);
addChild(burger);
burger.x = 100 + 100*i;
burger.y = 50;
}
addEventListener(Event.ENTER_FRAME, checkCollision);
function checkCollision(event:Event)
{
for (var i:uint=0; i<array.length; i++)
{
if (array[i].hitTestObject(bullet))
{
removeChild(array[i]);
array.splice(i,1);
return;
}
}
}
Thanks for any help.
No, you would not have to create each movie clip separately if you use a loop to create randomized x and y locations for each burger. You can also use Math.random() to give a random speed and direction to each burger. In the code below these values are held in "direction_ary" array. This code creates five MovieClips of the "Burger"class, and places them at random points on the screen. The code also creates random speeds and directions for each MovieClip:
import flash.events.Event;
function find_random(max,min){
return Math.round(min+(max-min)*Math.random());
}
var ary:Array = [];
var direction_ary:Array = [];
for(var i:uint=0;i<5;i++){
ary[i]=new Burger();
ary[i].name="burger"+(i);
ary[i].x=find_random(stage.stageWidth-ary[i].width,ary[i].width);
ary[i].y=find_random(stage.stageHeight-ary[i].height,ary[i].height);
addChild(ary[i]);
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
for(var e:uint=0;e<100;e++){
if(direction_ary[i][0]==0||direction_ary[i][1]==0){
direction_ary[i]=[find_random(5,-5),find_random(5,-5)];
}else{
break;
}
}
}
stage.addEventListener(Event.ENTER_FRAME,update_burgers);
function update_burgers(e:Event){
for(var i:uint=0;i<5;i++){
if (ary[i].x>stage.stageWidth||ary[i].x<0){
direction_ary[i][0]*=-1;
}
if (ary[i].y>stage.stageHeight||ary[i].y<0){
direction_ary[i][1]*=-1;
}
ary[i].x+=direction_ary[i][0];
ary[i].y+=direction_ary[i][1];
}
}
The code is fairly self explanatory. Good luck with your project.
Cheers,
Drake Swartzy

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.