Let’s say I have an object like this…
var objA = {
x:0,
y:0,
speed:{x:0, y:0},
angle:0,
turnSpeed:8
}
…and I each “step” in a game I want to move it towards objB, which is at coordinates (10, 10). ObjA is already moving and suddenly needs to move to objB’s position. Let’s say objA has a function turnTo() which can turn it towards objB each step based on its turnSpeed. I could do something like…
objA.speed.x += Math.cos((90 - obj.angle) * Math.PI / 180);
objA.speed.y += -Math.sin((90 - obj.angle) * Math.PI / 180);
…to move objA towards objB based on the angle, but if objA is already moving, it is unlikely to ever hit objB because this doesn’t take into account objA’s current speed.
How can I calculate a path to objB so that objA will hit it precisely?
First, take a look at Coordinates for my Javascript game – based on an angle, when do I use Sin Cos and Tan?
You know the x and y coordinates of objB (I assume they remain constant) and you can get the x and y coordinates of objA using JavaScript, thus you can solve the problem as a triangle from any point objA is to objB using simple trig.