Last active
December 14, 2020 15:03
-
-
Save UtMan88/83e62d434c19944a03d7a2c2476f24e6 to your computer and use it in GitHub Desktop.
Simple 2D Steering Algorithm for Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class SimpleSteerUtility | |
{ | |
// This is more of an example to show how the interface functions can be used in a very simple manner. | |
// Or, this can be your one-stop shop for a single function call in your Update function. | |
public static void SimpleSteer(ref Quaternion rotation, // ex: transform.rotation | |
ref Transform transform, | |
Vector3 dir, // target - position, normalized | |
Vector3 up, // ex: transform.up | |
ref Vector3 velocity, // should be stored in your monobehaviour | |
ref float speed, | |
ref Vector3 position, // ex: transform.position | |
float rotationSpeed, | |
float rotationMax | |
) | |
{ | |
rotation = getSteerRotation(rotation, dir, rotationSpeed * Time.timeScale, rotationMax); | |
velocity = (speed * up) * Time.deltaTime; | |
transform.position += velocity * Time.timeScale; // Timescale added for pausing | |
} | |
// Another interface to the meat of this algorithm, this version returns a velocity-esque Vector3 | |
// So you can use that as a force, or an impulse, or whatever. | |
public static Vector3 VelocitySteer(ref Vector3 position, | |
Vector3 forward, | |
Vector3 steerTo, | |
ref Quaternion rotation, | |
float moveSpeed, | |
float rotationSpeed, | |
float rotationMin, | |
float rotationMax) | |
{ | |
Vector3 dir = steerTo - position; | |
dir.Normalize(); | |
rotation = getSteerRotation(rotation, dir, rotationSpeed * Time.timeScale, rotationMax); | |
return (moveSpeed * forward) * Time.deltaTime; | |
} | |
// Very simple Algorithm that utilizes lookAt and RotateTowards to simulate Steering. | |
// However, we calculate out the angle we have to move in using Atan2 to provide a 2D "LookAt" | |
// So our object doesn't try to flip over. | |
public static Quaternion getSteerRotation(Quaternion rotation, | |
Vector3 dir, | |
float rotationSpeed, | |
float rotationMax) | |
{ | |
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg; | |
Quaternion lookAt = Quaternion.AngleAxis(angle - 90, Vector3.forward); | |
return Quaternion.RotateTowards(rotation, lookAt, rotationMax * rotationSpeed); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment