Search code examples
actionscript-3box2dgame-physicspath-findinggame-development

AS3 Box2D Player Movement


When creating a player with AS3 and Box2D we can get the player to move however we can't get the player to move like it would if it was just being moved with AS3 for example x++; as opposed to ApplyImpulse(new b2Vec2(1,0),GetWorldCenter()). How can we get the player to move more like flash, we have also tried ApplyForce and SetPosition which don't work correctly! The player is very floaty or doesn't instantly respond to controls, any advice would be greatly appreciated!

If there is a problem would you please explain it instead of downing and leaving?


Solution

  • Why don't you try using GetLinerVelocity and then a ApplyImpulse, it could work I made with this proprieties and of course I made two function before with the exactly keys...I mean something like :

    The player_normal is just the Player (object) in repose. And of course the player_max_speed and the player_speed are just other proprieties I add to move as I like...

                player_speed = 2;
                player_max_speed = 4;
                player_normal = new b2Vec2(0, 0);
    

    This goes in the function Main. The speed and max_speed you set them as a Number var, and the normal is just b2Vec2.

    And this is the key function when you press down and then up the key:

    private function apreto(e:KeyboardEvent):void
            {
                switch (e.keyCode)
                {
                    case 37: 
                        left = true;
                        break;
    } 
    
    private function suelto(e:KeyboardEvent):void
            {
                switch (e.keyCode)
                {
                    case 37: 
                        left = false;
                        break;
    }
    

    Of course the "left" is a boolean. Very easy I think..And you have to do the same with every key (right, up, down) it depends what kind of key you want it. For example the number 37 = key left in the keyboard.

    And then the code to give movement the player(in the update):

    if (player_normal.x >= 0)
                {
                    if (left)
                    {
                        if (player.GetLinearVelocity().x > -player_max_speed)
                        {
                            player.ApplyImpulse(new b2Vec2( -player_speed, 0), player.GetWorldCenter());
                        }
                    }
                }
    

    I hope it could help you...if not let me know, I have an other way that could be more easy. If I can answer any of your question I will be grateful to help.