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

// GDnD wiki example
// Demonstrates: driving a Vehicle2D toward a target or the mouse position
// Related pages: [[steering-behaviours]], [[overview-unity-nature-of-code-examples]]
 
using UnityEngine;
 
[RequireComponent(typeof(Vehicle2D))]
public class SeekArriveDemo : MonoBehaviour
{
    [SerializeField] private Transform target;
    [SerializeField] private bool targetFollowsMouse = true;
    [SerializeField] private bool useArrive = true;
 
    private Camera cachedCamera;
    private Vehicle2D vehicle;
 
    private void Awake()
    {
        vehicle = GetComponent<Vehicle2D>();
        cachedCamera = Camera.main;
    }
 
    private void Update()
    {
        Vector2 targetPosition = ResolveTargetPosition();
        Vector2 steering = useArrive
            ? vehicle.Arrive(targetPosition)
            : vehicle.Seek(targetPosition);
 
        vehicle.ApplyForce(steering);
    }
 
    private Vector2 ResolveTargetPosition()
    {
        if (target != null)
        {
            return target.position;
        }
 
        if (!targetFollowsMouse || cachedCamera == null)
        {
            return vehicle.Position;
        }
 
        Vector3 mouse = Input.mousePosition;
        mouse.z = Mathf.Abs(cachedCamera.transform.position.z);
        Vector3 world = cachedCamera.ScreenToWorldPoint(mouse);
        world.z = 0f;
        return world;
    }
}