Reputation: 3249
Here's a quick description of what some of the methods you'll see do:
this.bounds
: Returns the ship's bounds (a rectangle)this.bounds.getCenter()
: Returns a Vector2d
representing the center of the ship's bounds.getVelocity()
: A Vector2d
which represents the ship's velocity (added to position every frame)new Vector2d(angle)
: A new Vector2d
, normalized, when given an angle (in radians)Vector2d#interpolate(Vector2d target, double amount)
: Not linear interpolation! If you want to see the interpolate
code, here it is (in class Vector2d
):
public Vector2d interpolate(Vector2d target, double amount) {
if (getDistanceSquared(target) < amount * amount)
return target;
return interpolate(getAngle(target), amount);
}
public Vector2d interpolate(double direction, double amount) {
return this.add(new Vector2d(direction).multiply(amount));
}
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
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