Uncategorized

Unity3D mouse follow script

I wrote this script to have a GameObject follow the mouse cursor, converting mouse position to whatever coordinate space you need. I use it with viewport space to display grid coordinates next to the cursor with a GUIText component.

[code language=”csharp”]
using UnityEngine;

public class MouseFollow : MonoBehaviour
{
new public Camera camera;
public float zValue = 0;

public enum CoordinateSystem
{
World,
Screen,
Viewport
}
public CoordinateSystem convertTo;
new Transform transform;

void Awake()
{
transform = GetComponent<Transform>();
}

void Start()
{
if (camera == null)
{
camera = Camera.main;
}
}

void Update()
{
Vector3 converted = Input.mousePosition;

if (convertTo == CoordinateSystem.World)
{
converted = camera.ScreenToWorldPoint(converted);
} else if (convertTo == CoordinateSystem.Screen)
{
// Input.mousePosition is already in screen space
} else if (convertTo == CoordinateSystem.Viewport)
{
converted = camera.ScreenToViewportPoint(converted);
}

converted.z = zValue;
transform.position = converted;
}
}
[/code]

Leave a Reply