MCMastery
MCMastery

Reputation: 3249

Decelerate while moving in direction

Here's a quick description of what some of the methods you'll see do:

When the player is not pressing keys, the ship should just decelerate. Here's what I do for that:

public void drift() {
    setVelocity(getVelocity().interpolate(Vector2d.ZERO, this.deceleration));
}

However, now I've realized I want it to drift while going toward a target. I've tried this:

public void drift(Vector2d target) {
    double angle = this.bounds.getCenter().getAngle(target);
    setVelocity(getVelocity().interpolate(new Vector2d(angle), this.deceleration));
}

This of course won't ever actually reach zero speed (since I'm interpolating toward an angle vector, which has a magnitude of 1). Also, it only really "drifts" in the direction of the target when it gets very slow.

Any ideas on how I can accomplish this? I just can't figure it out. This is a big question so thanks a lot.

This is using a big library I made so if you have any questions as to what some stuff does please ask, I think I've covered most of it though.

Upvotes: 1

Views: 206

Answers (1)

MBo
MBo

Reputation: 80297

Your interpolate function does strange things. Why not use simple physical models? For example:

Body has position (px, py) and velocity (vx, vy), also unit direction vector (dx, dy) is convenient

After (small) time interval dt velocity changes depending on acceleration

vx = vx + ax * dt
vy = vy + ay * dt

Any outer force (motor) causes acceleration and changes velocity

ax = forcex / mass  //mass might be 1
ay = forcey / mass

Dry friction force magnitude does not depend on velocity, it's direction is reverse to velocity

ax = c * mass * (-dx)
ay = c * mass * (-dy)

Liquid friction force magnitude depends on velocity (there are many different equations for different situations), it's direction is reverse to velocity

ax = k * Vmagnitude * (-dx)
ay = k * Vmagnitude * (-dy)

So for every time interval add all forces, find resulting acceleration, find resulting velocity, change position accordingly

Upvotes: 1

Related Questions