AS3 Character jumping/falling problems - actionscript-3

I am having problems with getting the character to jump/fail when the up arrow is pressed. I'm trying to make it so when the up arrow key is pressed once it will jump a certain height then fall.
Here is my movement code:
public var gravity:int = 2;
public function fireboyMovement(e:KeyboardEvent):void
{
if (e.keyCode == 37) //right
{
fireboy1.x = fireboy1.x -5;
checkBorder()
}
else if (e.keyCode == 39) //left
{
fireboy1.x = fireboy1.x +5;
checkBorder()
}
if (e.keyCode == 38) //up
{
fireboy1.y = fireboy1.y -20;
fireboy1.y += gravity;
checkBorder()
}

Your issue is you need to increment the players position over time (and not all at once).
You can either use a tweening engine (like tweenlite), or roll your own timer or enter frame handler.
Here is an example of the latter:
if (e.keyCode == 38) //up
{
if(!isJumping){
isJumping = true;
velocity = 50; //how much to move every increment, reset every jump to default value
direction = -1; //start by going upwards
this.addEventListener(Event.ENTER_FRAME,jumpLoop);
}
}
var isJumping:Boolean = false;
var friction:Number = .85; //how fast to slow down / speed up - the lower the number the quicker (must be less than 1, and more than 0 to work properly)
var velocity:Number;
var direction:int = -1;
function jumpLoop(){ //this is running every frame while jumping
fireboy1.y += velocity * direction; //take the current velocity, and apply it in the current direction
if(direction < 0){
velocity *= friction; //reduce velocity as player ascends
}else{
velocity *= 1 + (1 - friction); //increase velocity now that player is falling
}
if(velocity < 1) direction = 1; //if player is moving less than 1 pixel now, change direction
if(fireboy1.y > stage.stageHeight - fireboy1.height){ //stage.stageheight being wherever your floor is
fireboy1.y = stage.stageHeight - fireboy1.height; //put player on the floor exactly
//jump is over, stop the jumpLoop
this.removeEventListener(Event.ENTER_FRAME,jumpLoop);
isJumping = false;
}
}

Related

ActionScript3: What code should I use to stop the player controlled sprite from moving?

I'm very new to ActionScript3 and am making an asteroids-type game. Right now, the ship continues floating in a straight line when you let go of the movement buttons, and I want to be able to stop that from happening. I'm thinking either a dedicated button for braking, like the b key, or if the keys are not pressed to stop movement, whichever would be easier. Like I said I'm really new to AS3 so not even sure what part of my code is making them keep flying in a straight line. Here is the code to control movement for reference:
// register key presses
public function keyDownFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = true;
} else if (event.keyCode == 39) {
rightArrow = true;
} else if (event.keyCode == 38) {
upArrow = true;
//Add event listener for down arrow
} else if (event.keyCode == 40) {
downArrow = true;
// show thruster
if (gameMode == "play") ship.gotoAndStop(2);
} else if (event.keyCode == 32) { // space
var channel:SoundChannel = shootSound.play();
newMissile();
} else if (event.keyCode == 90) { // z
startShield(false);
var channel:SoundChannel = shieldSound.play();
}
}
// register key ups
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
} else if (event.keyCode == 38) {
upArrow = false;
//Add listener for down arrow
} else if (event.keyCode == 40) {
downArrow = false;
// remove thruster
if (gameMode == "play") ship.gotoAndStop(1);
}
}
// animate ship
public function moveShip(timeDiff:uint) {
// rotate and thrust
if (leftArrow) {
ship.rotation -= shipRotationSpeed*timeDiff;
} else if (rightArrow) {
ship.rotation += shipRotationSpeed*timeDiff;
} else if (upArrow) {
shipMoveX += Math.cos(Math.PI*ship.rotation/180)*thrustPower;
shipMoveY += Math.sin(Math.PI*ship.rotation/180)*thrustPower;
//Added down arrow movement to allow player to move backwards
} else if (downArrow) {
shipMoveX -= Math.cos(Math.PI*ship.rotation/180)*thrustPower;
shipMoveY -= Math.sin(Math.PI*ship.rotation/180)*thrustPower;
}
// move
ship.x += shipMoveX;
ship.y += shipMoveY;
I agree that there is a little logic problem in your code. Your ship will move on 'til
judgement day because the two variables responsible for the speed of it's motion - shipMoveX
and shipMoveY - aren't automatically degraded over time.
Now there are literally thousands of ways of how this could be achieved but let's keep things
simple.
You are using a class variable called thrustPower - make sure to set it to 0.1 and that the value of both shipMoveX & shipMoveY is 0.
Additionally add these class variables:
private var thrustHorizontal:Number = 0;
private var thrustVertical:Number = 0;
private var speed:Number = 0;
private var maxSpeed:Number = 5;
private var decay:Number = 0.97;
Replace the moveShip function with this:
public function moveShip(timeDiff:uint):void
{
thrustHorizontal = Math.sin(Math.PI * ship.rotation / 180);
thrustVertical = Math.cos(Math.PI * ship.rotation / 180);
// rotate and thrust
if (leftArrow)
{
ship.rotation -= shipRotationSpeed * timeDiff;
}
else if (rightArrow)
{
ship.rotation += shipRotationSpeed * timeDiff;
}
else if (upArrow)
{
shipMoveX += thrustPower * thrustHorizontal;
shipMoveY += thrustPower * thrustVertical;
}
else if (downArrow)
{
shipMoveX -= thrustPower * thrustHorizontal;
shipMoveY -= thrustPower * thrustVertical;
}
if (!upArrow && !downArrow)
{
shipMoveX *= decay;
shipMoveY *= decay;
}
speed = Math.sqrt((shipMoveX * shipMoveX) + (shipMoveY * shipMoveY));
if (speed > maxSpeed)
{
shipMoveX *= maxSpeed / speed;
shipMoveY *= maxSpeed / speed;
}
ship.x += shipMoveX;
ship.y -= shipMoveY;
}
As you can see, there is this new if-block:
if (!upArrow && !downArrow)
{
shipMoveX *= decay;
shipMoveY *= decay;
}
Here we're handling the case, if the player neither pressed up nor down and multiply
the spaceships horizontal/vertical speed by decay. If you scroll back a bit, you notice
it's value is 0.97.
You can generally say, if you multiply a positive number x by 0 < y < 1, x will become smaller.
So if you're spaship is currently moving horizontally at 3 pixels per frame (shipMoveX=3 ; shipMoveY=0)
it will become 2.91 the next frame. The next frame it will be 2.8227, then 2.738019 ... and so on before it will finally reach zero in infinity.

Character jumping but not returning to ground platform game AS3

I am making a platform game where the main character moves right and left and jumps however my character jumps and does not return to the ground but stays on top of the stage.My characters movie-clip symbol is called 'naruto' and my ground symbol is called 'ground'.
Here is my code:
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;
naruto.gotoAndStop("stance");
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var narutoSpeed:Number = 10;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME,gameLoop);
function keyDownHandler(keyEvent:KeyboardEvent):void
{
if (keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
}else if(keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if (keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
naruto.gotoAndStop("standright")
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
naruto.gotoAndStop("standleft")
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
naruto.gotoAndStop("stance")
}else if(keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
naruto.gotoAndStop("stance")
}
}
function gameLoop(loopEvent: Event): void {
//If the right key is pressed, and the left key is NOT pressed
if (rightPressed && !leftPressed) {
naruto.x += narutoSpeed;
naruto.gotoAndStop("right");
}
if(leftPressed && !rightPressed) {
naruto.x -= narutoSpeed;
naruto.gotoAndStop("left");
}
var jumpHeight =0;
var defaultJumpSpeed = 20;
var jumpSpeed = 20;
if(upPressed && naruto.hitTestObject(ground))
{
trace("HELLO!");
naruto.y -= jumpSpeed;
jumpSpeed-= 4;
}
if(upPressed)
{
trace("HELLO!");
jumpHeight++;
naruto.y -= jumpSpeed;
if(jumpHeight>10)
jumpSpeed -= 4;
}
if(naruto.hitTestObject(ground))
{
trace("HELLO!");
jumpHeight =0;
jumpSpeed = defaultJumpSpeed;
}
}
Here is the link for my work: https://www.mediafire.com/?8d5opy49fuqmup5
Here is the problem:
The main issue, is in your current code, the player can only possible be in 3 positions:
Whatever the ground position is
16 (up is pressed and the character was not touching the ground
12 (up is pressed and the character was touching the ground)
Please see the code comments next to your original code to explain what is happening:
//you have this var inside the game loop, so every loop it resets to 20
var jumpSpeed = 20;
//so here, if up is pressed and the character is touching the ground
//you initiate a jump
if(upPressed && naruto.hitTestObject(ground))
{
trace("HELLO!");
naruto.y -= jumpSpeed;
jumpSpeed-= 4; //since you reset jumpSpeed to 20 every loop, this value will always just be 16
}
if(upPressed)
{
trace("HELLO!");
jumpHeight++;
//if naruto is touching the ground
//you are subtracting jumpSpeed above and right here again.
//so now the y position is 12 if touching the ground (or 16 if not touching the ground)
//since you reset jumpSpeed to 20 every loop, it always be one of those two values
naruto.y -= jumpSpeed;
if(jumpHeight>10)
jumpSpeed -= 4; //this serves no purpose, as your not using the value again and it gets reset to 20 next time the game loop runs
}
//this hit test will succeed in addition to the first one above when your jump starts.
if(naruto.hitTestObject(ground))
{
trace("HELLO!");
jumpHeight =0;
jumpSpeed = defaultJumpSpeed;
}
To remedy your jumping, you'll need to do something along these lines:
//initialize these vars outside of the game-loop for efficient and proper scoping (so their values don't reset every frame)
var isJumping:Boolean = false; //a flag to know if a jump is in progress
var jumpSpeed:Number = 0; //the current velocity of the jump
var defaultJumpSpeed:Number = 20; //the initial force (speed) of a jump
var jumpGravity:Number = 2; //subtract this from the speed every frame to slow the jump over time and fall
var onGround:Boolean = false; //a helper var for efficiency
function gameLoop(loopEvent: Event): void {
//If the right key is pressed, and the left key is NOT pressed
if (rightPressed && !leftPressed) {
naruto.x += narutoSpeed;
naruto.gotoAndStop("right");
}
if (leftPressed && !rightPressed) {
naruto.x -= narutoSpeed;
naruto.gotoAndStop("left");
}
//only do the hit test once per frame for efficiency (store the result)
onGround = naruto.hitTestObject(ground);
if (upPressed && onGround) {
trace("START JUMP");
isJumping = true;
jumpSpeed = defaultJumpSpeed; //set the initial jump velocity
}
if(isJumping){ //if jumping
naruto.y -= jumpSpeed; //move the player based off the current jump velocity
jumpSpeed -= jumpGravity; //slow the jump every frame (eventually causing it to be negative making the player fall)
}
//touching the ground and the up key is not pressed
//it's very important to put !upPressed so this doesn't run at the time as the initial jump above
if (!upPressed && onGround) {
//stop any jump motion
jumpSpeed = 0;
isJumping = false;
//you probably also want to snap the player to the ground
naruto.y = ground.y - naruto.height + 2; //the plus 2 ensures that the ground and the player touch so the hit test succeeds
}
}

AS3: Swipe Gesture With Velocity

So I would like to add velocity to my swipe gesture. Currently I have it moving 10 px on swipe, but I want it to move with a velocity so the user can toss the object around on the screen. Here's the code I am currently using with the object moving the 10 px.
function onSwipe (e:TransformGestureEvent):void{
player_mc.gotoAndStop(5);
if (e.offsetX == 1) {
//User swiped towards right
player_mc.x += 10;
}
if (e.offsetX == -1) {
//User swiped towards left
player_mc.x -= 10;
}
if (e.offsetY == 1) {
//User swiped towards bottom
player_mc.y += 10;
}
if (e.offsetY == -1) {
//User swiped towards top
player_mc.y -= 10;
}
if(collision(player_mc.cp, level_mc))
{
player_mc.x = player_mc.prevX;
player_mc.y = player_mc.prevY;
}
}
Thanks for the help
Here is a way you can do this: (you'll want to swap the mouse events for touch events if using on mobile)
player_mc.addEventListener(MouseEvent.MOUSE_DOWN,startSwipe);
player_mc.addEventListener(MouseEvent.MOUSE_UP,endSwipe);
var velocity:Point = new Point(); //this stores the current velocity of the object
var previous:Point = new Point(); //this stores the previous frames x/y of the object.
var isDragging:Boolean = false;
var friction:Number = .85; //this how quickly to slow down the object once the mouse is released - smaller the number (must be less than 1) the quicker the object will slow/stop
function startSwipe(e){
isDragging = true;
player_mc.startDrag(false);
this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}
function enterFrameHandler(e):void {
if(isDragging){
velocity.x += player_mc.x - previous.x; //we're adding the new velocity to the old one, then dividing in half to average the value - this makes it seem smoother
velocity.y += player_mc.y - previous.y;
velocity.x *= .5; //dividing in half
velocity.y *= .5;
previous.x = player_mc.x;
previous.y = player_mc.y;
}else{
velocity.x *= friction; //gradually slow down the object
velocity.y *= friction;
player_mc.x += velocity.x;
player_mc.y += velocity.y;
if(velocity.x < .05 && velocity.y < .05){ //once it gets slow enough, stop the enter frame handler
this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
}
}
trace(velocity);
}
function endSwipe(e){
player_mc.stopDrag();
isDragging = false;
}

AS3 - Skip not Move

I'm making a frogger game in AS3 and when you press up, down, left and right, you "skip" a certain amount of space instead of gradually moving there like in most platformers now. How would I be able to do this?
Currently he moves up left, down and right on their respective keys. But he gradually moves there, not skipping the amount of space like in the real frogger.
Any ideas on how I could do this?
Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyDownHandler(event:KeyboardEvent):void{
if (event.keyCode == Keyboard.UP){
trace("frogger up");
player.y -= 5;
}
if(event.keyCode == Keyboard.DOWN){
trace("frogger down");
player.y += 5;
}
if(event.keyCode == Keyboard.LEFT){
trace("frogger left");
player.x -= 5;
}
if(event.keyCode == Keyboard.RIGHT){
trace("frogger right");
player.x += 5;
}
}
One way to do is to increase the X and Y with a certain amount like as Marty said in the comment, with 50.. or you could create two variables, let's name them xPosition & yPosition.
When holding down the keys, you would just increase/decrease these variables by 1, and then call a positioning function which would calculate the new position of the player depending on the xPosition and yPosition 's values and of course the grid sizes.
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
var xPosition:int = 0;
var yPosition:int = 0;
var gridWidth:int = 32;
var gridHeight:int = 32;
function keyDownHandler(event:KeyboardEvent):void{
if (event.keyCode == Keyboard.UP){
yPosition--;
repositionPlayer();
}
if(event.keyCode == Keyboard.DOWN){
yPosition++;
repositionPlayer();
}
if(event.keyCode == Keyboard.LEFT){
xPosition--;
repositionPlayer();
}
if(event.keyCode == Keyboard.RIGHT){
xPosition++;
repositionPlayer();
}
}
function repositionPlayer():void{
player.x = gridWidth*xPosition;
player.y = gridHeight*yPosition;
}
This gives you a big advantage in case you want to change the grid size.

Player velocity will never go to zero after collision?

My collision code is supposed to inverse the x velocity and reduce it to a third, then when the player is not pressing either "A" or "D" keys, the velocity should slowly reduce to zero, however, once the player collides the velocity only reduces to a small decimal between .25 and .70 (either positive or negative based on previous directions.)
//Function to determine what to do with keys
function KeyHandler():void{
//A Key Handlers
if(aKeyPressed == true){
if(Math.abs(_vx) < MaxSpeed){
_vx += -6;
}
}
//Player _vx somehow won't hit zero!!!
else if(aKeyPressed == false){
if(_vx < 0){
_vx += 1;
}
}
//D Key Handlers
if(dKeyPressed == true){
if(Math.abs(_vx) < MaxSpeed){
_vx += 6;
}
}
else if(dKeyPressed == false){
if( _vx > 0){
_vx += -1;
}
}
//W Key Handlers
if(wKeyPressed == true){
if(Jumped == false){
_vy = -15;
Jumped = true;
}
}
else if(wKeyPressed == false){
}
}
//Code for Right Collision
if(RightCollision){
while(RightCollision){
Player.x -= 0.1;
RightCollision = false;
if(_boundaries.hitTestPoint((Player.x + (Player.width / 2)), (Player.y - (Player.height / 2)), true)){RightCollision = true;}
}
_vx *= -.33
}
//Code for Left Collision
if(LeftCollision){
while(LeftCollision){
Player.x += 0.1;
LeftCollision = false;
if(_boundaries.hitTestPoint((Player.x - (Player.width / 2)), (Player.y - (Player.height / 2)), true)){LeftCollision = true;}
}
_vx *= -.33
}
Note that abs(-.25) + abs(.7) ~ 1.0
The collision sets the velocity to something that is not an integer (e.g. 2 * .33 ~ .7), so +/- 1 will skip past 0 without landing on it.
The simple fix is to keep the velocity an integer which can be done with Math.floor, for instance. (Account for the difference in +/- velocities: floor only moves numbers one direction.)
Happy coding.
Also, I am not sure how the int type works in AS3 work, which might be worth exploring.