Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created July 4, 2019 18:07
Show Gist options
  • Save beardordie/b8493349c7b075a5e47371bd01cecdcf to your computer and use it in GitHub Desktop.
Save beardordie/b8493349c7b075a5e47371bd01cecdcf to your computer and use it in GitHub Desktop.
Unity - simple 2D auto rotation component with nice Gizmo, separated from Unity Playground, added a rotation type, follows Open/Closed principle
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class AutoRotator2D : MonoBehaviour
{
public enum AutoRotateType
{
AddForceEveryFrame,
AddTorqueImpulse
}
public bool AutoStart = true;
public AutoRotateType rotationType = AutoRotateType.AddForceEveryFrame;
// This is the force that rotate the object every frame
public float rotationForce = 10f;
public Mesh gizmoRotateArrowMesh; // use this: https://github.com/Unity-Technologies/UnityPlayground/blob/master/Assets/_INTERNAL_/Resources/Meshes/RotateArrow.fbx
protected new Rigidbody2D rigidbody2D;
protected bool hasStarted = false;
protected virtual void Awake()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
protected virtual void Start()
{
if (AutoStart && rotationType == AutoRotateType.AddTorqueImpulse)
{
AddTorqueImpulse();
}
}
[ContextMenu("Begin Rotation")]
public virtual void BeginRotation()
{
AutoStart = false;
hasStarted = true;
if (rotationType == AutoRotateType.AddTorqueImpulse)
{
AddTorqueImpulse();
}
}
protected virtual void AddTorqueImpulse()
{
rigidbody2D.AddTorque(rotationForce);
hasStarted = true;
}
protected float currentRotation;
// FixedUpdate is called once per frame
protected virtual void FixedUpdate()
{
if (AutoStart && rotationType == AutoRotateType.AddForceEveryFrame)
{
RotateTick();
hasStarted = true;
}
else if (!AutoStart && hasStarted && rotationType == AutoRotateType.AddForceEveryFrame)
{
RotateTick();
}
}
protected virtual void RotateTick()
{
// Find the right rotation, according to speed
currentRotation += .02f * rotationForce * 10f;
// Apply the rotation to the Rigidbody2d
rigidbody2D.MoveRotation(-currentRotation);
}
//Draw an arrow to show the direction in which the object will rotate
protected virtual void OnDrawGizmosSelected()
{
if (enabled)
{
DrawRotateArrowGizmo(transform.position, rotationForce);
}
}
protected virtual void DrawRotateArrowGizmo(Vector3 position, float strength)
{
Gizmos.color = Color.green;
Gizmos.DrawMesh(gizmoRotateArrowMesh, position, Quaternion.identity, new Vector3(Mathf.Sign(strength), 1f, Mathf.Sign(strength)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment