0

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: enter image description here 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: enter image description here 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.)

Community
  • 1
  • 1
NonCreature0714
  • 5,744
  • 10
  • 30
  • 52
  • Let's say `x` is horizontal distance between your sprite and mouse click and `y` is the vertical distance, you can get the rotation by `Arctan(y/x)` , Then you set that rotation on your `transform.rotation` – Arijoon Jun 23 '16 at 21:05
  • 1
    never, ever, ever touch quaternions or .rotation. simply use "Rotate" to make it rotate. if you do want to simply set the angles, just .eulerAngles = – Fattie Jun 23 '16 at 21:59

1 Answers1

0

Have few options in this example, that which axis you want to look towards mouse: https://gist.github.com/unitycoder/5366a610599b503a40e9

mgear
  • 1,333
  • 2
  • 22
  • 39