- Hits: 925
Follower 2D
Needed: Unity Free or Pro
Simple but accurate follow script for 2D rigidbodies. Just attach it to a 2D game object and assign a target.
When you had problems with the orientation of your Ridgidody2D while following an object have a look to this script.
Code
using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] public class Follower2D : MonoBehaviour { /// <summary> /// The target <c>GameObject</c>. /// </summary> public GameObject Target; public float MoveSpeed = 2, AngularSpeed = 45; /// <summary> /// Angle threshold. When the angle is smaller than this value, no recalculations are performed. /// </summary> public const float Threshold = 1e-3f; public void Update() { LookAt(); Move(); } /// <summary> /// Looks at the <c>Target</c> game object. /// </summary> public void LookAt() { Vector2 dir = transform.InverseTransformPoint(Target.transform.position); float angle = Vector2.Angle(Vector2.right, dir); angle = dir.y < 0 ? -angle : angle; if (Mathf.Abs(angle) > Threshold) { transform.Rotate(Vector3.forward, AngularSpeed * Time.deltaTime * Mathf.Sign(angle)); } } /// <summary> /// Moves toward the target. /// </summary> public void Move() { rigidbody2D.MovePosition(transform.position + (transform.right * MoveSpeed * Time.deltaTime)); } }