Trouble calculating angle between an object and mouse position

Hey guys,

I am creating a 2.5d game, where a character who’s position is fixed on the screen, fires a projectile to where ever the mouse is located. I only want an angle around the Z axis, so that the projectile is fired along the X and Y. I tried using this code initially which is attached to the character:

angle = Vector3.Angle(transform.position, Input.mousePosition);

When I debugged angle, the values were very odd, there weren’t values that I could use to angle my projectiles. I understand that I need to convert the radians to degrees, but when I moved the mouse around the character, the value was between 60 and 90, so something can’t be right. Here is a picture which probably explains what I’m trying to accomplish more clearly:

If I can find out that angle, I can instantiate a projectile at a rotation which is equal to the angle, and add relative force to send it toward the mouse location.

If someone could let me know where I’m going wrong, or state the steps I need to take to accomplish this, that would be greatly appreciated.


the mouse exists on the x and y plane, the object exists in three dimensions

your trying to get the angle between a (x,y,z) and (x,y,z = 0?)

you should first find the right z, the right z is the z of the object.

Alternatly you could pretend the object is 2d for the purposes of this calculation.

something like

vector2.angle(new vector2(object.transform.x, object.transform.y), mouse.position)

That was all just for more info though, your actually doing that in a too complicated way, since your trying to fire from the Red object to the mouse.

The red object is the character and the mouse is what you’d like to fire towards and the slope of the line between them know both points is an easy thing to find.

You can find a direction (aka the slope of a line) which goes from one point to another by subtracting where your want to go from where your going from. this basically makes where you going from 0 and the x,y,z == slope then or the direction to go.

direction = mouse.position - player.transform.position

you now instantiate a project at player position and use that direction.

Lastly you could do it EVEN MORE SIMPLY.

create an object and use the lookat function. That makes the front of the object looks at a given point. It does it how i told you but unity does the math for you.


now the direction to travel is forward with transform or add force going toward projectile.forward with physics.

Since your using a 3d engine but making a 2d game, get the mouse position and set the z depth equal to the objects z depth as stated earlier.

vector3 MousePos = new vector3(mouse.position.x, mouse.position.y, player.transform.position.z)

click the checkmark under the down arrow and mark as answered. good luck!