 Author Topic: Moving a Hero in a game  (Read 1704 times)

dca

• Member
•  • Posts: 11
• Karma: +0/-0 Moving a Hero in a game
« 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)

• The sprite starts moving right at a constant speed.
• If you press the left arrow key it should move left; right arrow key move right. When the key is pressed it should speed up, then slow down to the constant speed. The more you press a key, the faster it goes in that direction before slowing down again.
• If the sprite is on the right side of the screen, and no keys are pressed, it will continue right at a constant speed. The same goes for the left.

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!

sheep42

• Member
•  • Posts: 12
• Karma: +0/-0 Re: Moving a Hero in a game
« Reply #1 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;
}

@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();
}
}