Home > Software engineering >  LibGDX: Scale Movement Projection Line to Always be the Same Length
LibGDX: Scale Movement Projection Line to Always be the Same Length

Time:09-17

I'm working on a game in LibGDX. Right now, I am working on drawing a line from a moving entity's body current position in the direction that it is moving. Maybe I didn't word that correctly, so here's my very artistic representation of what I'm talking about.

Entity jumps, moving up and right: draw line from entity up and left

Entity moves right: draw line from entity to right

The problem that I'm having is that vertical lines are always much longer than diagonal lines, and diagonal lines are always much longer than horizontal lines. What I'm wanting is for the line being projected from the entity to always be the same length regardless of the direction.

Below is the code used for drawing lines from the center of an entity's body. As you can see, I am scaling the line (e.g., by 25.0f). Maybe there's a formula that I could use to dynamically change this scalar depending on the direction?

public class BodyMovementProjection implements Updatable {

    public final Body body;
    public final ShapeRenderer shapeRenderer;

    public boolean debugProjection = false;
    public float scalar = 25.0f;

    private final Vector2 posThisFrame = new Vector2();
    private final Vector2 posLastFrame = new Vector2();
    private final Vector2 projection = new Vector2();
    
    private float[] debugColorVals = new float[4];

    public BodyMovementProjection(Body body) {
        this.body = body;
        this.shapeRenderer = body.entity.gameScreen.shapeRenderer;
    } // BodyMovementProjection constructor

    @Override
    public void update() {
        body.aabb.getCenter(posThisFrame);
        posLastFrame.set(posThisFrame).sub(body.bodyMovementTracker.getSpritePosDelta());
        projection.set(posThisFrame).sub(posLastFrame).scl(scalar).add(posLastFrame);
        if (debugProjection) {
            shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
            shapeRenderer.setColor(debugColorVals[0], debugColorVals[1], debugColorVals[2], debugColorVals[3]);
            shapeRenderer.line(posLastFrame, projection);
            shapeRenderer.end();
        } // if
    } // update

    public void setDebugColorVals(float r, float g, float b, float a) {
        debugColorVals[0] = r;
        debugColorVals[1] = g;
        debugColorVals[2] = b;
        debugColorVals[3] = a;
    } // setDebugColorVals

} // BodyMovementProjection

CodePudding user response:

Normalize before you scale. By normalizing you are making the directional vector 1 unit in length, and by scaling it after by 25 you get a vector that is 25 units every time, regardless of how far apart thw current and previous positions are.

  • Related