Archived

This topic is now archived and is closed to further replies.

spoolinEG

Finding angle on two 2d objects

Recommended Posts

I have finished all the 2d collision detection I need. The problem is I need to figure out the angle from one object (x1,y1) to another object (x2,y2), but once I do that how can I figure out what to add/subtract to what axis so I can send a projectile from one object to another?

Share this post


Link to post
Share on other sites
I learned that at standard grade(GCSE level).

Basically what you do is find the gradient(m) with this formula:

m = (y2-y1)/(x2-x1)

Once you have found m(the gradient) you know the gradient to project the object at in a straight line from one point to the another.

the angle(in degrees) between the x-axis(horizontal) and m(the gradient line) is ((tan)^-1)m.

Theta = (inverse tan)m

[edited by - chris_ward1000 on April 5, 2004 6:23:58 PM]

[edited by - chris_ward1000 on April 5, 2004 6:24:38 PM]

Share this post


Link to post
Share on other sites
atan2 is a better choice in my opinion. It''s been debated endlessly on these forums, and I''ll stick to my guns

float dx = x1 - x0;
float dy = y1 - y0;
float angle = atan2(dy, dx);

Share this post


Link to post
Share on other sites
Thanks for the replys, but I probobly should have specified.. x1/y1 is the characters position, x2/y2 is the position of the mouse, so the mouse can go on any side of the character, and I need to shoot a projectile from the character to the mouse. I cant figure out how to do it.. I know how to get the angles but how do I do that to work with pixels? Thanks..

Share this post


Link to post
Share on other sites
If you're using angles, you're losing something fundamental.

You already know (or should know) where your gun is pointed, as a vector. Use that vector as the "front" vector of your projectile movement; scale it by velocity.

For example, if your rotation is stored as a quaternion, you can get front (or back, for right-handede systems) out by converting to matrices, and using the first 3 elements of the third column as "front" (the columns of a matrix are just the world space directions of that matrix's basis vectors).


Oh, and just saw the second clarification. An even easier way to do this is to take the vector from player to mouse (which is (x',y') == ((x2-x1),(y2-y1)), normalize it (which means multiply by 1/sqrtf(x'*x' + y'*y')), and then multiply by the speed of your projectile. This is how the projectile will move, in 2D. Each step, just add this velocity to the projectile position.

[edited by - hplus0603 on April 5, 2004 9:59:12 PM]

Share this post


Link to post
Share on other sites
hplus, could you explain 1/sqrtf(x''*x'' + y''*y''))? this will only give me one velocity right? the velocity for x/y wouldnt be the same right?

Share this post


Link to post
Share on other sites