Skip to content

Instantly share code, notes, and snippets.

@kugimasa
Created February 23, 2023 13:24
Show Gist options
  • Save kugimasa/06cb33906ddb4ae7d8ef97745493aff9 to your computer and use it in GitHub Desktop.
Save kugimasa/06cb33906ddb4ae7d8ef97745493aff9 to your computer and use it in GitHub Desktop.
Unity MonoBehaviour code for XY/YZ planer circular movement of an object.
using UnityEngine;
public class CircularMotionXY: MonoBehaviour
{
[SerializeField, Range(0, 1000)] private float _Speed;
[SerializeField, Range(1, 100)] private float _Radius;
[SerializeField] private Transform _Center;
private float _theta = 0.0f;
void Update()
{
if (_theta >= 360.0f) _theta = 0.0f;
_theta += _Speed * Time.deltaTime;
var theta = Mathf.Deg2Rad * _theta;
var x = _Radius * Mathf.Cos(theta) + _Center.position.x;
var y = _Radius * Mathf.Sin(theta) + _Center.position.y;
var z = transform.position.z;
transform.position = new Vector3(x, y, z);
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(_Center.position, _Radius);
}
}
using UnityEngine;
public class CircularMotionYZ : MonoBehaviour
{
[SerializeField, Range(0, 1000)] private float _Speed;
[SerializeField, Range(1, 100)] private float _Radius;
[SerializeField] private Transform _Center;
private float _theta = 0.0f;
void Update()
{
if (_theta >= 360.0f) _theta = 0.0f;
_theta += _Speed * Time.deltaTime;
var theta = Mathf.Deg2Rad * _theta;
var x = transform.position.x;
var y = _Radius * Mathf.Sin(theta) + _Center.position.y;
var z = _Radius * Mathf.Cos(theta) + _Center.position.z;
transform.position = new Vector3(x, y, z);
}
void OnDrawGizmos()
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(_Center.position, _Radius);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment