- Home /
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:
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.
Answer by robertbu · Dec 15, 2013 at 09:26 AM
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[i];
Thanks I'll give this a go, and translate it into C#. Thanks
Well I tried to translate it. Turns out "angle" has to be a float. Ok, I tried converting it to and int and it didn't work. Do you $$anonymous$$d rewriting this in C#?
using UnityEngine;
using System.Collections;
public class Facing : $$anonymous$$onoBehaviour {
void Update() {
Vector3 screenPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 direction = Input.mousePosition - screenPos;
float angle = $$anonymous$$athf.Atan2(direction.y, direction.x) * $$anonymous$$athf.Rad2Deg;
if (angle < 0.0f)
angle = 360.0f + angle;
angle += 22.5f;
int i = (int)(angle / 45.0f);
i = i % 8;
Debug.Log(i);
}
}
Your answer
Follow this Question
Related Questions
How do i change sprite regarding to position 1 Answer
2D lock x,y rotation to look at target 2 Answers
My sprites wont change? 0 Answers
unity 2D help 0 Answers