Source file unity-csharp/nature-of-code/seek-and-arrive-2d/TargetFollower.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: moving a visual target marker with the mouse in Unity 2D
// Related pages: [[steering-behaviours]], [[overview-unity-nature-of-code-examples]]
 
using UnityEngine;
 
public class TargetFollower : MonoBehaviour
{
    [SerializeField] private float zDepth = 0f;
 
    private Camera cachedCamera;
 
    private void Awake()
    {
        cachedCamera = Camera.main;
    }
 
    private void Update()
    {
        if (cachedCamera == null)
        {
            return;
        }
 
        Vector3 mouse = Input.mousePosition;
        mouse.z = Mathf.Abs(cachedCamera.transform.position.z);
 
        Vector3 world = cachedCamera.ScreenToWorldPoint(mouse);
        transform.position = new Vector3(world.x, world.y, zDepth);
    }
}