Sign in to follow this  

I need help finding an angle. (2d)

Recommended Posts

I'm using this to get the information I need to make a sprite follow the mouse cursor. but I want to also get the angle so that I can make the sprite point to the cursor. can I do it from here or do I need to use another method for my math?
         homer.xDist = spriteX - posX;
	homer.yDist = spriteY - posY;

	homer.totalDist = sqrt(homer.xDist*homer.xDist + homer.yDist*homer.yDist);

	homer.xVel = homer.xDist/homer.totalDist;
	homer.yVel = homer.yDist/homer.totalDist;

Share this post

Link to post
Share on other sites
You have one vector (sprite -> pos). You need another vector to create an angle. Usually this is a reference vector such as (1, 0).

The dot product of two (normalized) vectors is the cosine of the angle between those vectors. So, some pseudocode:

v1 = pos - sprite;
v2 = (1, 0);
ca = dot(v1, v2);
angle = acos(ca);

(This isn't complete, actually atan2 would be better, as already mentioned.)

Now, one question to ask is: do you really need the angle? Some people take that angle and throw it back into generating a matrix or similar. In that case, you can avoid the acos call. If you are thinking of calling cos(angle), then skip the acos call, cause ca is what you already want.

Share this post

Link to post
Share on other sites
Original post by scgrn
Look up the atan2() function. It returns radians, so you'll want to divide it by (PI/180) to convert it to degrees.


that worked. I had to tweak the math abit, since for some reason the sprite rotation stuff I got a hold of has somewhere around 6 making up a full circle. so I had to use atan2 (homer.yVel,homer.xVel) + (3.1415/2 + 3.1415) to get the sprite to point to the cursor.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this