Physically based Characters!

Hello…World!

So this just gave me a good run for my money for a while. For the longest time, I’ve been building all of my Characters completely wrong and the bug didn’t really surface until this latest game. Lets start by talking about what a Physically based Character even is.

What is a physically based character

1. A game object which is controlled by a player with input.

2. Reacts to the physics system in conjunction with player input.

So what was I doing wrong before?

Almost every tutorial you will ever find tells you how to build a 2D Character pretty much wrong, and this is what the movement code probably looks like:

        Vector2 newVelocity = this.cachedBody.velocity;
        newVelocity.x += xSpeed * this.maxSpeed;
        this.cachedBody.velocity = newVelocity;

Lets talk about why this code won’t work for a physically based character.  Because it resets the velocity every frame!  So if my character gets a force added to it from an explosion or is sliding down a hill, the x component of the velocity using this strategy will be reset every frame to the input.

So how do I do it right?

Doing it right is exactly the same number of lines.

        Vector2 pos = this.cachedBody.position;
        pos.x += xSpeed;
        this.cachedBody.position = pos;

So in this, we are just adding to the position the input quantity, xSpeed.  This allows the physics system to have complete control over velocity, we don’t touch it at all, and we move the rigidbody’s actual position giving us an “addative” effect ontop of the physics system, which is what we want.  Now when I shoot Mr. Jack Round out of the cannon, he flies out, interacts with the world physically while I still am able to give my players input control over him while aligning with the physics system.

This is how I will be moving almost all of my characters from here on out.

Leave a Reply

Your email address will not be published. Required fields are marked *