Speed keeps stacking in actionscript 3.0 - actionscript-3

We have been making this game for our class CPT and you play as a character and try to get through these levels but the issue is that every time you die and go back to play the level again the speed stacks on top of the previous speed to a point where the game isn't even playable anymore. We have tried resetting it and setting it back to 0 but nothing seems to work we also tried to code it so that is the speed goes past 21 it resets back to 20 (our ideal speed) we also tried to remove extra event listeners that could have been stacking on top of the other. and if you do happen to die but get to the next frame the speed goes back to 20 for that frame.But if you die on that frame it doubles the speed on that frame too.Our code is:
import flash.events.Event;
import flash.display.MovieClip;
//makes the character jump
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, whenKeyPressed);
stage.addEventListener(Event.ENTER_FRAME, update);
function whenKeyPressed(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(event:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
//when the character makes it to the other side of the screen, the frame
changes
if (player_mc.hitTestObject(frameChanger1))
{
gotoAndStop(91);
}
//end the game when the character touches the penguin
if (player_mc.hitTestObject(penguin1))
{
gotoAndStop(89);
}
}
//makes the character move left and right
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
player_mc.addEventListener(Event.ENTER_FRAME, moveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, setKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, unsetKeyPressed);
function moveInDirectionOfKey(event:Event)
{
if (leftPressed)
{
player_mc.x -= 20;
}
if (rightPressed)
{
player_mc.x += 20;
}
}
function setKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function unsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
}
//when the character makes it to the other side of the screen, the frame
changes
if (player_mc.hitTestObject(frameChanger1))
{
gotoAndStop(91);
}
//end the game when the character touches the penguin
if (player_mc.hitTestObject(penguin1))
{
gotoAndStop(89);
}
}

Did You tried :
if(!stage.hasEventListener(Event.ENTER_FRAME)){
stage.addEventListener(Event.ENTER_FRAME, update);
}
if(!stage.hasEventListener(KeyboardEvent.KEY_DOWN)){
stage.addEventListener(KeyboardEvent.KEY_DOWN, setKeyPressed);
}
if(!stage.hasEventListener(KeyboardEvent.KEY_UP)){
stage.addEventListener(KeyboardEvent.KEY_UP, unsetKeyPressed);
}
if(!player_mc.hasEventListener(Event.ENTER_FRAME)){
player_mc.addEventListener(Event.ENTER_FRAME, moveInDirectionOfKey);
}
And so on...
Otherwise You will register the Events multiple times...
This may be the issue.
I'm not sure, I avoid to code on multiple frames.
You may also use the answer of #Philarmon here Function being called faster

Related

Actionscript 3.0: Cannot get key input

guys. I created a little game. Nothing actually happening thought, because im not getting my keyboard input. I spend some time trying to create my own taht didnt work. Then I copy/pasted code from official actionscript 3.0 reference page, but tweaked it for my game (but I didnt touch anything related to keyboard stuff). Also the only thing my game returns in cosnole is false
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;
stop();
var left = false;
var right = false;
var speed = 0.3;
player.addEventListener(KeyboardEvent.KEY_DOWN, keydF);
player.addEventListener(KeyboardEvent.KEY_UP, keyuF);
player.addEventListener(Event.ENTER_FRAME, updF);
function keydF(event:KeyboardEvent):void {
trace("test0");
if(event.keyCode == Keyboard.D) {
trace("test1");
left = true;
}
if(event.keyCode == Keyboard.A) {
right = true;
}
}
function keyuF(event:KeyboardEvent):void {
trace("test2");
if(event.keyCode == Keyboard.D) {
left = false;
}
if(event.keyCode == Keyboard.A) {
right = false;
}
}
function updF(e:Event):void {
if(left) {
level.x -= speed;
}
if(right) {
level.x += speed;
}
trace(left + ""); //always false :\
}
If you want to get the key input to your app, you should add the listeners to the stage :)

Actionscript 3 Making the character to Jump

I am making a platformer game. But I am having issue because whenever I pressed the spacebar to jump, the character will stuck in the mid-air. However, I can resolved the problem by holding spacebar and the character will land.
The issue is at mainJump() located inside Boy class.
I seen many people solved the problem by using action timeline, but my main problem is, are there anyway I can solve the problem by using an external class?
Main class
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 5;
//whether or not the main guy is jumping
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var theCharacter:MovieClip;
var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, boyMove);
}
public function boyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (currentY >= stage.stageHeight - MovieClip(this).height)
{
mainJumping = false;
currentY = stage.stageHeight - MovieClip(this).height;
}
}
}
}
First of all, formalize your code, eliminating sassy things like 'pressTheDamnKey,' which doesn't even describe the function very well because a function cannot press a key. That is an event handler and should be named either keyDownHandler or onKeyDown, nothing else.
Secondly, you rarely want to do any actual work in event handlers beyond the immediate concerns of the event data. Instead call out to the function which does the actual work. A handler handles the event, then calls the code which does the work. This separates out concerns nicely for when you want something else to be able to also make the little boy animate besides the enterFrameHandler, like perhaps a mouse.
I can imagine your trace log is getting filled up pretty quickly with "Score" lines since your timer is firing 100 times a second (10 milliseconds per). I would change that to not fire on a timer, but to be refreshed when the score actually changes.
The problem with the jumping, aside from spaghetti code, is that you are basing his movements upon whether the key is pressed or not by saving the state of the key press in a variable and having him continually inspect it. This is bad for a couple of reasons: 1. he should not need to reach out to his environment for information, it should be given to him by whatever object owns him or by objects that are responsible for telling him and 2. It requires you to continually hold down the spacebar or he will stop moving, since he checks to see if it is being held down (see problem 1).
I will address all these issues below, leaving out the scoring, which is another matter altogether.
package
{
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.*;
// Sprite is preferred if you are not using the timeline
public class Application extends Sprite
{
private var boy:Boy;
public function Application()
{
boy = new Boy();
addChild(boy);
boy.x = 600; // set these here, not in the boy
boy.y = 540;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler );
}
public function keyDownHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
case 32: boy.jump();
break;
case 37: boy.moveLeft();
break;
case 39: boy.moveRight();
break;
default:
// ignored
break;
}
}
public function keyUpHandler(event:KeyboardEvent):void
{
switch(event.keyCode)
{
// ignored for jumping (32)
case 37: // fall through
case 39: boy.stop();
break;
default:
// ignored
break;
}
}
}//class
}//package
package
{
import flash.display.*;
import flash.events.*;
// It is assumed that there is an asset in the library
// that is typed to a Boy, thus it will be loaded onto
// the stage by the owner
public class Boy extends Sprite
{
private var horzSpeed :Number = 0;
private var vertSpeed :Number = 0;
private var floorHeight :Number;
private var jumpHeight :Number;
private var amJumping :Boolean = false;
public function Boy()
{
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
public function moveLeft():void
{
horzSpeed = -1;
}
public function moveRight():void
{
horzSpeed = 1;
}
public function stop():void
{
horzSpeed = 0;
}
public function jump():void
{
if (amJumping) return;
floorHeight = y;
jumpHeight = floorHeight + 20;
vertSpeed = 2;
amJumping = true;
animateJump();
}
private function enterFrameHandler(event:Event):void
{
animate();
}
private function animate():void
{
x += horzSpeed;
if( amJumping )
{
animateJump();
}
}
// Doing a simple version for this example.
// If you want an easier task of jumping with gravity,
// I recommend you employ Greensock's superb
// TweenLite tweening library.
private function animateJump():void
{
y += vertSpeed;
if( y >= jumpHeight )
{
y = jumpHeight;
vertSpeed = -2;
}
else if( y <= floorHeight )
{
y = floorHeight;
amJumping = false;
}
}
}//class
}//package
Another way to approach this, and probably the better way long-term, is for the boy to not even be responsible for moving himself. Instead, you would handle that in the parent, his owner or some special Animator class that is responsible for animating things on schedule. In this even more encapsulated paradigm, the boy is only responsible for updating his own internal look based upon the outside world telling him what is happening to him. He would no longer handle jumping internally, but instead would be responsible for doing things like animating things he owns, like his arms and legs.
You've got a mainJumping variable that is only true while the jump is running. Why not just use that?
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}

Continuos Timer and object for a game AS3

I am currently working on a game where you need to survive as long as possible while dodging questions that come your way. (all with AS3)
At the moment I am going from 1 scene to another in between the game field and the question field, but everytime I go to the question scene the timer in the game scene resets itself. I was wondering if it was possible to have the timer continue while being in the question scene?
Also I have a movable character in between the menus which incidentally are also made in different scenes and the player is able to move him around, and I would very much like him to stay in the last position he was in the next screen, as in I move him to the top right in the main menu and when I go to the options menu I want him to still be in the top right and not in his initial position.
As for my timer this is the code I am using at the moment:
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.globalization.DateTimeFormatter;
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}
And my character is using this code:
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.
Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
rutte.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)
{
rutte.y -= 5;
}
if (downPressed)
{
rutte.y += 5;
}
if (leftPressed)
{
rutte.x -= 5;
rutte.scaleX = 1; // face left
}
if (rightPressed)
{
rutte.x += 5;
rutte.scaleX = -1; // face right
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
Thank you in advance for all the help you can give me.
Kind Regards.
in flash there is a fundamental aspect of how timeline and scenes works. Once you move away from a frame to another frame, The content of the frame and it's properties/states/actions are gone and reseted.
Personally I recommend you use a single scene with a timeline divided into frames labeled, there you can specify a layer for the actions and global variables, one for the user interface and another one for the specific actions of each frame. example:
So you never lose the reference of variables because the frame is not constantly recreated, all your important actions, including you timer, should be in your first frame.
I was testing, here you can see a working example: http://db.tt/FZuQVvt3. Here you can download the FLA file to be used as a base for your project: http://db.tt/RHG9G5lo

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. AS3

i'm trying to make a space invaders type game with bullets shooting and ships crashing into one another using the hitTestObject function but i can't get the removeChild(); function to work without the Error above. Here's the Code what should i do.
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.display.MovieClip;
var count:int = 1;
//adding the components
var NewBullet:MovieClip = new Bullet;
var Ship_M:MovieClip = new Ship;
Ship_M.x = 270;
Ship_M.y = 470;
addChild(Ship_M);
var Ship_E:MovieClip = new E_Ship;
Ship_E.x = 270;
Ship_E.y = 5;
addChild(Ship_E);
stage.addEventListener(Event.ENTER_FRAME , Rec);
function Rec(e:Event):void{
if (NewBullet.hitTestObject(Ship_E))
{
removeChild(Ship_E);
removeChild(NewBullet);
}
if (Ship_E.hitTestObject(Ship_M))
{
removeChild(Ship_E);
removeChild(Ship_M);
}
}
function Moves(e:Event):void{
NewBullet.y -= 30;
if (NewBullet.y < 0 )
{
removeChild(NewBullet);
count++;
removeEventListener(Event.ENTER_FRAME, Moves);
}
trace (count);
}
//For Moving the Spaceship
stage.addEventListener(KeyboardEvent.KEY_DOWN, Move);
function Move (event:KeyboardEvent):void{
switch(event.keyCode)
{
case 37:
if (Ship_M.hitTestObject(Stop_L1))
{
Ship_M.x -= 0;
}
else
{
Ship_M.x -= 10;
}
break;
case 38:
if (Ship_M.hitTestObject(Stop_U1))
{
Ship_M.x -= 0;
}
else
{
Ship_M.y -= 10;
}
break;
case 39:
if (Ship_M.hitTestObject(Stop_R1))
{
Ship_M.x -= 0;
}
else
{
Ship_M.x += 10;
}
break;
case 40:
if (Ship_M.hitTestObject(Stop_D1))
{
Ship_M.x -= 0;
}
else
{
Ship_M.y += 10;
}
break;
case 32:
addChild(NewBullet);
NewBullet.x = Ship_M.x;
NewBullet.y = Ship_M.y;
addEventListener(Event.ENTER_FRAME, Moves);
break;
default:
}
}
Replace yours
removeChild(SomeSprite);
with
if (SomeSprite.parent)
SomeSprite.parent.removeChild(SomeSprite);
An objects parent can only call removeChild.
You may not need this in your particular circumstance, but I have a helper function to remove a child and make it eligible for GC which goes like so:
private function remove(child:DisplayObject):void
{
if(child && child.parent)
{
child.parent.removeChild(child);
child = null;
}
}
Most likely you do removeChild(NewBullet) twice, first when it hits Ship_E and second when it leaves boundary. A simple solution will be whenever your NewBullet is removed from stage, set it a flag, say "enabled" which would mean the bullet can trigger events, and check it throughout your code whenever you have to check for the bullet.
Note, you have only one bullet, is it normal?

How to do you get an character to jump?

This is my fist time ever needing to use this for one of my games. I want to have the character jump. I have been trying to get this result for about an hour, but with no luck =( I am using AS3, and flash CS5.5. So far all my code does is make the character go left, and right based on keyboard input. Could someone please help?
Here is my code so far:
public class Dodgeball extends MovieClip
{
public var character:Character;
public var rightDown:Boolean = false;
public var leftDown:Boolean = false;
public var speed:Number = 3;
public var timer:Timer;
public function Dodgeball()
{
character= new Character();
addChild(character);
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, MyKeyUp);
timer = new Timer(24);
timer.addEventListener(TimerEvent.TIMER, moveClip);
timer.start();
}
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.RIGHT)
{
rightDown = true;
if(character.currentLabel != "walkingRight")
{
character.gotoAndStop ("walkingRight");
}
}
if (event.keyCode == Keyboard.LEFT)
{
leftDown = true;
if (character.currentLabel != "backingUp")
{
character.gotoAndStop("backingUp");
}
}
}
public function MyKeyUp(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.RIGHT)
{
character.gotoAndStop("standing");
rightDown = false;
}
if (event.keyCode == Keyboard.LEFT)
{
character.gotoAndStop("standingLeft");
leftDown = false;
}
}
public function moveClip(event:TimerEvent):void
{
if (rightDown)
{
character.x += speed;
}
if (leftDown)
{
character.x -=speed;
}
event.updateAfterEvent();
}
}
}
One method you can try is found here: http://www.actionscript.org/forums/showthread.php3?t=256009 Like your speed variable, grav determines the vertical position of the character.
var grav:Number = 10;
var jumping:Boolean = false;
var jumpPow:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(Event.ENTER_FRAME, update);
function onKeyDown(evt:KeyboardEvent):void
{
if(evt.keyCode == Keyboard.UP)
{
if(jumping != true)
{
jumpPow = -50;
jumping = true;
}
}
}
function update(evt:Event):void
{
if(jumping)
{
player_mc.y += jumpPow;
jumpPow += grav;
if(player_mc.y >= stage.stageHeight)
{
jumping = false;
player_mc.y = stage.stageHeight;
}
}
}
Edit: Jason's method is fine, but I'm not sure if it would be useful if you plan to have some kind of collision detection.
What I would do is create a motion tween of the character jumping. then call gotoAndPlay on that frame, and on the last frame of the tween put a stop, or a gotoAndStop on the "stationary" frame, or whatever frame represents a neutral position.
if (event.keyCode == Keyboard.SHIFT)
{
character.gotoAndPlay("simpleJump");
jumpDown = false;
}
This will give you the greatest animation control over the look and feel. You could also do it programmatically, but personally, I recommend against it. It will take less time to set it up, and you can tweak and refine the jump animations later. You could make several types of jump animations based on object near the target etc.
I would also change this stuff:
if(character.currentLabel != "walkingRight")
By defining a new function where you have all the rules for when and where something can be done, so that in your control logic, you just call
if(characterCan(character,"walkright")) ...
Where characterCan(String) is a method that check if this is possible. For instance, if you are jumping and shooting, you obviously cannot walk right, so in the end, you will have to start adding pieces of logic into those if statements and it's gonna become a cluttered mess.
A very simple approach is to have a vertical speed as well as a horizontal speed.
When the user presses "UP" or "JUMP", set y speed to a negative value and update it in your movieClip function. When the character gets to a certain height, reverse the speed.
Using gravity and acceleration looks better but this is a really good place to start. Look into kinematic equations to see how you would make the character accelerate.
public var originalY;
public function myKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.UP && vSpeed == 0)
{
originalY = character.y;
ySpeed = -1;
}
}
public function moveClip(event:TimerEvent):void
{
if (vSpeed != 0)
{
character.y += vSpeed;
/* make the character fall down after reaching max jump height */
if(originalY - character.y > jumpHeight) {
vSpeed = vSpeed * -1;
}
/* level the character after he's hit the ground (so he doesn't go through) */
else if(character.y >= originalY) {
character.y = originalY;
vSpeed = 0;
}
}
}