Patrik
Patrik

Reputation: 2247

Calculate the direction based on degrees

So I'm working on a particle emitter with javascript and canvas.
And I want to be able to set what direction the particles are emitting based on an angle.

This can be done with this function:

y = Math.tan(45 * Math.PI/180);

Which returns 1 if the angle is 45. etc.

But I don't exacly know how I should implement this since pixels are calculated a little different. Think -1 as removing one pixel each step and 1 as adding one pixel.

If the angle is 45, Y is 1 and X is 1 which is correct.
But to get a pixel traveling at 315 degrees Y is -1 and X should be 1.
And at 225 degrees Y should be -1 (but is 1) and X should be -1.

How should the function look like if it should work like this?

Here is an image of how im thinking:
(The emitter is in the origin.)

The emitter is in origin

Upvotes: 2

Views: 1568

Answers (2)

duffymo
duffymo

Reputation: 308763

It sounds to me like your problem is that you're thinking about direction, which is a vector quantity, as if it were a scalar.

You need to remember that a 2D vector is represented as two components:

enter image description here

enter image description here

You can work in terms of unit vectors, so the magnitude r = 1.

So if you have a direction angle, which should be measured in radians, increasing in the counterclockwise direction, and starting at the x = 0 horizontal axis, you'll end up with two components of the unit vector that points in the direction you want.

Upvotes: 0

totten
totten

Reputation: 2817

Actually it's simple,

angle = (angle * Math.PI/180) % 360;
tangent = Math.tan(angle);

Since you do not know where is x;

section_x_positive = (angle<90||angle>270?1:-1);
section_y_positive = (angle>0&&angle<180?1:-1);
x = abs(tangent) * section_x_positive;
y = abs(tangent) * section_y_positive;

Upvotes: 1

Related Questions