- Home /
C# LookAt Mouse 2D
Hello, i'm trying to do a code to player look at mouse, but i'm a beginner and don't know how to do it exatly, here is my code:
using UnityEngine;
using System.Collections;
public class PlayerBehaviour : MonoBehaviour {
public Transform target;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.LookAt(target);
}
}
I need to put mouse in target, but how? Or i need to do other code? Somebody can save me with that? I'm using C#, thanks =(
And sorry for my bad english
Answer by robertbu · Sep 15, 2014 at 10:24 PM
Try this:
void Update() {
Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
Answer by Stormizin · Sep 15, 2014 at 09:00 PM
You need to get the mouse position relative to the game screen, and always on Update function make your character turn around looking the mouse pointer.
See Mouse Position, Rotate, and other things
Your answer
Follow this Question
Related Questions
2D Topdown Shooter Enemy Knockback 0 Answers
Difficulty with my tank game 2 Answers
How in the world do I ACCURATELY place an object at the mouse? 3 Answers
2D camera zoom smoothing and limitations? 1 Answer
Evac city outdated? 0 Answers