Created
February 23, 2023 13:24
-
-
Save kugimasa/06cb33906ddb4ae7d8ef97745493aff9 to your computer and use it in GitHub Desktop.
Unity MonoBehaviour code for XY/YZ planer circular movement of an object.
This file contains hidden or 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 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); | |
} | |
} |
This file contains hidden or 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 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