I have a character in a 2D game, my goal is to get his eyes look as if they are looking at the cursor by moving the circles used for pupils towards the cursor, with limits. I have been stuck trying to create this for two days now and have yet to find a way that works!! Using the following code I was able move my eyes towards the cursor, however this only works around the bottom left of the screen! (If the cursor is not below the screen or to the left of the screen the eyes move to the top right)
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour {
public float speed = 5f;
private Vector3 target;
public Transform origin;
void Start () {
target = transform.position;
}
void Update () {
target = (Input.mousePosition);
target.z = transform.position.z;
transform.position = Vector3.MoveTowards(origin.position, target, speed * Time.deltaTime);
}
}
If anyone could point me in the right direction I would be incredibly grateful! Thank you :)
Likely the reason it's only working in one quadrant for you is because Input.mousePosition
returns a position in pixel coordinates. Basically, if your window is 800x600 pixels, it will return...
(0, 0, 0) for the bottom left pixel of the screen
(0, 600, 0) for the top left pixel of the screen
(800, 0, 0) for the bottom right pixel of the screen
(800, 600, 0) for the top right pixel of the screen
Since your eye pupil is in world space, you want the mouse position in world space also. Either way, even if you fixed that, I don't think Vector3.MoveTowards
is going to do quite what you're wanting to do. I think this is more along the lines of what you want:
using UnityEngine;
public class LookAtMouse : MonoBehaviour {
public float speed = 5f;
public float maxDistance = 1f;
public Camera mainCamera;
private Vector3 _origin;
void Start () {
_origin = transform.position;
}
void Update () {
/* Get the mouse position in world space rather than screen space. */
var mouseWorldCoord = mainCamera.ScreenPointToRay(Input.mousePosition).origin;
/* Get a vector pointing from initialPosition to the target. Vector shouldn't be longer than maxDistance. */
var originToMouse = mouseWorldCoord - _origin;
originToMouse = Vector3.ClampMagnitude(originToMouse, maxDistance);
/* Linearly interpolate from current position to mouse's position. */
transform.position = Vector3.Lerp (transform.position, _origin + originToMouse, speed * Time.deltaTime);
}
}