I've made this script that gets a normalized Direction towards the mouse.
It does this based on your ViewPort, Just give it a shot and play around with it.
using UnityEngine;
using System.Collections;
public class NormMouse : MonoBehaviour {
public static NormMouse Instance;
void Awake() { Instance = this; }
Vector3 viewPortActual, viewPortDelta, directionToMouse;
///
/// Retrieves a Normalized Vector3 Direction from mPosition towards the MousePos
///
/// a Normalized Vector3 Direction from mPosition towards the MousePos (as WorldPos)
public Vector3 GetNormalizedDirectionToMouse()
{
// Calculate a direction based on the Mouse Position (using Viewport)
viewPortActual = Camera.main.ScreenToViewportPoint(Input.mousePosition);
viewPortDelta = new Vector3(0.5f, 0.5f, 0); // Detract Half the screen
directionToMouse = viewPortActual - viewPortDelta; // Caculate Direction
return directionToMouse.normalized; // Return normalized Direction
}
}
Here, I made another Class for you that looks at the position using my above code from afar :)
Make sure the NormMouse script is somewhere in the scene, and there can be only one of them, because Singleton is applied :)
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour {
Transform mTransform;
void Start()
{
mTransform = transform;
}
// Update is called once per frame
void Update () {
mTransform.LookAt(mTransform.position + NormMouse.Instance.GetNormalizedDirectionToMouse());
}
I think that's about the best explanation I can give you, but if you have any more questions, or need any details, fire away! If not, please accept this answer ;)
Best of luck ;3
↧