Created
February 14, 2022 15:03
-
-
Save MarcelvanDuijnDev/c207c2e326ceda50791e4c680c898f2a to your computer and use it in GitHub Desktop.
Unity Pendulum script
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 UnityEngine; | |
public class Pendulum : MonoBehaviour | |
{ | |
[Header("Settings")] | |
[SerializeField] private float _Speed = 1; | |
[SerializeField] private float _Distance = 20; | |
[Header("Offset")] | |
[SerializeField] private Vector3 _RotationOffset = Vector3.zero; | |
[SerializeField] private bool _SetCurrentRotationAsOffset = true; | |
enum AxisOptions { X, Y, Z } | |
[SerializeField] private AxisOptions _Axis = AxisOptions.X; | |
private void Start() | |
{ | |
if (_SetCurrentRotationAsOffset) | |
_RotationOffset = transform.eulerAngles; | |
} | |
void Update() | |
{ | |
float angle = _Distance * Mathf.Sin(Time.time * _Speed); | |
switch (_Axis) | |
{ | |
case AxisOptions.X: | |
transform.localRotation = Quaternion.Euler(_RotationOffset.x + angle, _RotationOffset.y, _RotationOffset.z); | |
break; | |
case AxisOptions.Y: | |
transform.localRotation = Quaternion.Euler(_RotationOffset.x, _RotationOffset.y + angle, _RotationOffset.z); | |
break; | |
case AxisOptions.Z: | |
transform.localRotation = Quaternion.Euler(_RotationOffset.x, _RotationOffset.y, _RotationOffset.z + angle); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks,
A version with more control over the angle + an optional period on the offset, so the swing can feel more natural for some organic cases.
Something like Offset (0,0,5) and Axis (1, 0, 0.2) is nice in our case for instance.