I need help finding an angle. (2d)

Started by
2 comments, last by escudo825 18 years, 1 month ago
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;

Advertisement
Look up the atan2() function. It returns radians, so you'll want to divide it by (PI/180) to convert it to degrees.

HTH
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.
Quote: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.

HTH


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.

This topic is closed to new replies.

Advertisement