How do I get my character to look in the direction of the cursor?

I’m make a top-down RPG and I wanted my character to be able to “look” around using the cursor. Here is what I mean:

19347-diagram.png

I want to do it this way so I can implement projectile weapons such as a bow and arrow and spells such as fireball, but I don’t know how to approach this. Answers appreciated.

How you implement this will depend on how you implement your character. You have many choices:

  • Use a Quad and an array of textures
  • Use a Quad and a sprite sheet. Manipulate the material offset and scale.
  • Use a Quad and a texture atlas and manipulate the uv coordinates of the quad.
  • Use Unity’s new Sprite
  • Use a third-party tool like NGUI or EZGUI

Regardless of your solution, a likely first step is translate the angle into an integer that can be used to select a texture from an array, or set a frame. Here is a bit of code that makes that translation:

#pragma strict
 
 function Update() {
 	var screenPos = Camera.main.WorldToScreenPoint(transform.position);
 	var direction = Input.mousePosition - screenPos;
 	var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
 	if (angle < 0.0)
 		angle = 360.0 + angle;
 	
 	angle += 22.5;
 	
 	var i : int = (angle / 45.0);
 	i = i % 8;
 	
 	Debug.Log(i);
}

‘i’ will be 0 when the cursor is within 22.5 degrees of directly to the right, and the integers increase counter clockwise. To test, put this script on a game object, run, and move the cursor around the object.

If you have an array of textures representing the 8 possible directions, you would use this code like:

renderer.material.mainTexture = textures*;*