In Unity3d, I'm trying to get a sprite to "look at" where I click my mouse. This similar question doesn't answer my question, because it is for libgdx and it is in Java, not C#. While this other question is also similar, it concerns XNA not Unity3d. Example in the Unity Documentation on Euler and Quaternion rotations here seems focused in non-interactive rotation.
I suspect ray casting may be part of a possible solution, but I was under the (possibly mistaken) impression it works best with colliders, which I'm not using. I'm pretty stumped right now and need some one more experienced to help.
It may also be I'm not quite handling/understanding (what seems like) 2d clicks in a 3d environment, with a 2d sprite. I only want the sprite to rotate in a 2d manner.
Again, I want to get the mouse's position while the right mouse button is clicked, calculate the angle between the GameObject and mouse click, and then point the object at the mouse click.
using UnityEngine;
using System.Collections;
public class LookAtClickPoint2d : MonoBehaviour {
public Vector3 mousePosition;
private Camera cam;
// Use this for initialization
void Start ()
{
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 targetDir = mousePosition - transform.position;
if (Input.GetMouseButton (1))
{
//transform.Rotate(targetDir); /*<---This is @joeblow's suggestion.*/
/*below is @mgear's suggestion*/
Vector3 perpendicular = Vector3.Cross(transform.position-mousePosition, Vector3.forward);
transform.rotation = Quaternion.LookRotation(Vector3.forward, perpendicular);
}
}
}
@mgear's answer gets me this:
While it's not obvious in the picture, the sprites only point at the center of the camera view, and not the mouse position.
@joeblow's answer gets me this:
While the sprites are pointed to the mouse position, they do not remain perpendicular. And they only move once! So it didn't answer my question.(I think somehow Unity is trying to interpret the mouse position in 3d space, and not 2d.)