I have a simple 2D system in which a velocity is represented as a speed (some value) and direction (an angle). If I have an object travelling at a given velocity v, when another velocity v2 acts upon it I want to calculate the resultant velocity v3.
I have created the following illustration to explain the physics system I wish to implement. The speeds and angles may not be exactly correct because I do not know how to calculate them yet - that is the crux of this question - yet they serve as a fairly close guideline.
Is there an elegant solution for calculating the resultant velocities v3, when new velocity v2 acts upon an object travelling at v?
Please note that I have a very limited understanding of mathematics but a good understanding of programming. I am coding in TypeScript but any answer in JavaScript, pseudo code, or very clear explanation (not riddled with cryptic mathematical symbols) is helpful.
The simplest solution consists in converting to cartesian coordinates, add the coordinates there, then convert back to polar coordinates.
converting to cartesian:
x = speed * cos(direction)
y = speed * sin(direction)
back to polar:
speed = sqrt(x * x + y * y)
direction = atan2(y, x)
It might be a better idea to store your velocities in cartesian coordinates.
Edit: using your variable names: v, v2, v3, and angles a, a2, a3:
x = v * cos(a)
y = v * sin(a)
x2 = v2 * cos(a2)
y2 = v2 * sin(a2)
x3 = x + x2
y3 = y + y2
v3 = sqrt(x3 * x3 + y3 * y3)
a3 = atan2(y3, x3)
So you have an object flying in the direction v1
.
In order to support velocities, you just have to add them to v1
for each frame / simulation step:
var v2;
while(simulation is running){
v1 = v1 + v2;
}
You can represent v1
, v2
as vectors with the components x
and y
.
In order to convert you values, you can use x = speed * cos(direction)
and y = speed * sin(direction)
as supposed by Rémi.
Your addition will then look as follows:
v1.x = v1.x + v2.x;
v1.y = v1.y + v2.y;
In order to get the angle of a vector, you can use the formula tan(angle) = y / x
, resulting in
angle = atan(y/x)
The according JavaScript call is var angle = atan2(v1.y, v1.x);
.
The length of your vector (= speed of you object) can be calculated with
speed = sqrt(v1.x * v1.x + v1.y * v1.y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With