Flixel Forums

development => help => Topic started by: dca on Tue, Nov 17, 2015

Title: Moving a Hero in a game
Post by: dca on Tue, Nov 17, 2015
Hello all,

I'm having a real tough time figuring this one out.

I have a Hero sprite and I need to do the following. (I can capture the right and left keys, just don't know the logic to get the sprite to move properly)


I can get the sprite to move left and right but the speed up/slow down I can't get. I've read tutorials but nothing is working for me

Thanks!
Title: Re: Moving a Hero in a game
Post by: sheep42 on Sat, Nov 21, 2015
I would do it by applying a constant x velocity and then modifying the x acceleration on key press. When no keys are pressed you can check the velocity and modify the acceleration accordingly. This is written in Flixel-GDX, meaning this is Java code, but it shouldn't be too difficult to change the syntax if you're in AS3 or Haxe. 

Code: [Select]
public class PlayState extends FlxState{
FlxSprite player = new FlxSprite(100, 100);

@Override
public void create(){
player.makeGraphic(20, 20, FlxG.BLUE);
player.velocity.x = 100;
add(player);
}

@Override
public void update(){
                //Screen Wrap
if(player.x >= FlxG.width + player.width){
player.x = -player.width;
} else if(player.x <= -(player.width+1)) {
player.x = FlxG.width;
}

                //Handle key presses
if(FlxG.keys.pressed("LEFT")) {
player.acceleration.x = -50;
} else if(FlxG.keys.pressed("RIGHT")) {
player.acceleration.x = 50;
} else {
                        //Check velocity and get back to the constant velocity
if(player.velocity.x > 100){
player.acceleration.x = -50;
} else if(player.velocity.x < 100) {
player.acceleration.x = 50;
} else {
player.acceleration.x = 0;
player.velocity.x = 100;
}
}

//Cap the velocity at 300 so the player doesn't accelerate to infinity
if(FlxG.keys.pressed("LEFT") || FlxG.keys.pressed("RIGHT")){
if(player.velocity.x > 300)
player.velocity.x = 300;
else if(player.velocity.x < -300)
player.velocity.x = -300;
}

super.update();
}
}