Random Direction

How would I find a random direction to send an object flying towards? Say I want to send an object flying towards 56 degrees how can I actually move an object in the x and y plane to that direction? Normally I would just have a x speed and y speed but when i make a random explosion effect I get a square.

1 1 1 1 1
1 1
1 0 1
1 1
1 1 1 1 1

0 is the origin of the explosion.

I want

1    

1 1
1 0 1
1 1
1

Can I just find a random number between 360 and send the object in that direction?


double angle = 10; //The shot angle
double moveSpeed = 10; //The speed of the shot

double xSpeed = Math.cos(angle) * moveSpeed;
double ySpeed = Math.sin(angle) * moveSpeed;

and also remember in which unit youj have your angles, radient or gradient. The MAth.* functions take radient i gues(?), take a look at the docs.

repeat theagentd’s code with diff angle value. for explosion fixed length can work too.

Yeah careful all the trig functions in the Math class use radians.


double angle = Math.random() * 2 * Math.PI;
double speed = 20;

double dX = speed * Math.cos(angle);
double dY = speed * Math.sin(angle);

Repeat to yourself: radians are your friend, degrees are for artist…

Ugh, too much OpenGL for me… xD

Thank you so much exactly what I was looking for…well I knew I wanted to find the radians of the angle with sin/cos but could not remember what to do with them. How much slower is this compared to just giving and x and y speed? Is the sin/cos that costly? I know you are not doing it on every move update but still.

Degrees are for openGL :wink:

If your computer is over 30 years old or if you have millions of objects, it may be costly. Otherwise you will not notice any slowdown.

If you are worried about performance, it is best to use this FastMath class, courtesy of Riven. This uses a lookup table, causing the trig functions to be over 50x faster.

This was what I was looking for but I am still getting a square. :o
Am I doing this wrong?

double speedX = 10Math.cos(angle);
double speedY = 10
Math.sin(angle);

Are you using 2 different angles for cos and sin? That’s the only possible way to get a square :wink:

No same angle but i forgot the pi…no pun intended. I got it working now and it is looking really freaking good…at least to me it is.

Nice! =D