Skip to content

Instantly share code, notes, and snippets.

@Nrjwolf
Last active July 1, 2020 08:32
Show Gist options
  • Save Nrjwolf/f89568c43a96f862fa2d20593cd1b24c to your computer and use it in GitHub Desktop.
Save Nrjwolf/f89568c43a96f862fa2d20593cd1b24c to your computer and use it in GitHub Desktop.
Homing Missile. The algorithm is taken from http://www.freeactionscript.com/tag/game-examples/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HomingMissile : MonoBehaviour
{
[GetComponent] [SerializeField] private Rigidbody2D m_Rigidbody2D;
public Rigidbody2D Rigidbody2D { get => m_Rigidbody2D; }
public Transform Target;
public float Speed = 5;
public float TurnRate = .7f;
public bool IsRotating = true;
public float RotatingOffset = 0; // zero —> sprite head in right side
private Vector3 m_Move;
private bool m_HasPhysics;
private void Start()
{
m_HasPhysics = Rigidbody2D != null;
}
private void FixedUpdate()
{
if (Target != null)
{
//get distance between follower and target
var distance = (Vector2)Target.position - Rigidbody2D.position;
//get total distance as one number
var distanceTotal = Mathf.Sqrt(distance.x * distance.x + distance.y * distance.y);
//calculate how much to move
Vector3 moveDistance = TurnRate * distance / distanceTotal;
//increase current speed
m_Move += moveDistance;
//get total move distance
var totalMove = Mathf.Sqrt(m_Move.x * m_Move.x + m_Move.y * m_Move.y);
//apply easing
m_Move = Speed * m_Move / totalMove;
}
if (IsRotating)
{
transform.rotation = Quaternion.Euler(0, 0, 180 * Mathf.Atan2(m_Move.y, m_Move.x) / Mathf.PI + RotatingOffset);
}
if (m_HasPhysics)
{
Rigidbody2D.velocity = m_Move;
}
else
{
transform.position = transform.position + m_Move;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment