Applying force immediately question ?

Posts that don't fit into other categories.
jojoofu
Posts: 3
Joined: Thu Mar 23, 2017 10:31 am

Applying force immediately question ?

Postby jojoofu » Fri Mar 24, 2017 8:38 pm

I'm creating a top down style video game control. I want the character to move up , down , left , right etc on key press. My current method is on the initial key press is to set the the linear force to the movement speed. Then each frame after I apply the movement via impulse. This will cause the character to move instantly at full speed in the direction specified.

I find when I'm close to walls if I use this method that sudden contact with a surface will cause the fixture to spin out of control for a moment the stop. I tried locking the angle by setting the angular force to 0 and and rotation to 0 each frame but it still happens.

I'm curious if there is a better way to move an object in a set speed in one direction , with the angular motion locked , while still using the physics engine ?

update * forgot the code ;)

Code: Select all

        // Lock the body upright.
        body.setAngularVelocity(0);
        body.getTransform().setRotation(0);

         if (game.input.key(LEFT).pressed){
            moveForce.set(-speed * delta , 0);
            body.setLinearVelocity(moveForce);
        }
         
        // move right
        if (game.input.key(RIGHT).pressed){
            moveForce.set(speed * delta, 0);
            body.setLinearVelocity(moveForce);
        }

        // move left
        if (game.input.key(LEFT).down){
            moveForce.set(-speed * delta , 0);
            body.applyImpulse(moveForce);
        }
         
        // move right
        if (game.input.key(RIGHT).down){
            moveForce.set(speed * delta, 0);
            body.applyImpulse(moveForce);
        }
   
        // jump
        if (game.input.key(JUMP).pressed){
            jump();
        }


Thanks,
Joe

P.S. I converted the physics over to JavaFX and made it a full fledged game engine for anyone who is interested.

William
Site Admin
Posts: 345
Joined: Sat Feb 06, 2010 10:23 pm

Re: Applying force immediately question ?

Postby William » Mon Mar 27, 2017 9:53 am

You can set the mass type of the body to FIXED_ANGULAR_VELOCITY so that the angular velocity of the body doesn't change. If you need to rotate the body, you would have to do it manually though.

Another option, if you didnt need to instantly change the speed of the body, you could use the MotorJoint class. There's some examples of this on the forum and in github. This is used specially so that weird things don't happen when a user controlled body hits other bodies.

William


Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 2 guests