I implemented some vector addition code for a 2d space sim that i’m working on that looks like this:
public class Vector2D implements Cloneable {
/**
* Angle in radians.
*/
private double angle;
/**
* Speed in units/second.
*/
private double speed;
/**
* Constructor: takes an angle in radians and a speed.
*/
public Vector2D(double ang, double spd) {
angle = ang;
speed = spd;
}
/**
* Rotates the angle by n radians.
*/
public void rotate(double n) {
angle += n;
}
/**
* Changes the speed by n.
*/
public void changeSpeed(double n) {
speed += n;
}
/**
* Accessors
*/
public double getAngle() {
return angle;
}
public double getSpeed() {
return speed;
}
/**
* Vector addition - takes another vector to which
* this vector should be added to and returns the resulting
* vector.
*/
public Vector2D add(Vector2D other) {
double angleC,newAngle, newSpeed;
angleC = Math.PI + angle - other.angle;
newSpeed = Math.sqrt((speed * speed) + (other.speed * other.speed) -
2 * speed * other.speed * Math.cos(angleC));
newAngle = angle + Math.asin((Math.sin(angleC)/newSpeed) * other.speed);
newAngle = Math.abs(newAngle % (2 * Math.PI));
return new Vector2D(newAngle, newSpeed);
}
public String toString() {
return "Angle: " + Math.toDegrees(angle) + " Speed: " + speed;
}
}
This code works great for steering my ship, (it looks just like it should), but it behaves very strangely with projectiles. If my ship is traveling at low speeds, (under 1000 pixels/sec), projectiles will only fire in a specified 180 degree region. For instance, if the ship is facing the way it’s actually going, or close to it, the projectile fires with the correct angle. However, if I turn the ship the opposite way of the direction it’s going, the projectile still fires the way the ship is going. To get the vector for the projectile, I just use my add method to add the vector of the ship and an arbitrary vector for the projectile:
if(keyboard.isPressed(FIRE_KEY)) {
Vector2D projVector = going.add(new Vector2D(facingTheta,800));
new Projectile(env,SpriteStore.loadImage("projectile.png"),getX() + width / 2,getY() + height / 2,10,10,projVector,300,0,this);
}
If the ship is travelling very fast, projectiles will fire in all directions with no error in their vectors. Can anyone explain why this happens, perhaps some flaw in the logic of my vector addition or an entirely different approach I should use?