Hello, i’m trying to make my gun rotate 360 degrees on the x axis across 2 seconds, I’ve tried searching online for an answer, but haven’t found anything yet, any help?
You can try to change the rotation property of transform component.
using UnityEngine;
public class Rotate : MonoBehaviour
{
public float SecondPassed, PeriodSeconds;
// Start is called before the first frame update
void Start()
{
PeriodSeconds = 2;
}
// Update is called once per frame
void Update()
{
SecondPassed = Time.time;
gameObject.transform.rotation = Quaternion.Euler(SecondPassed * (360 / PeriodSeconds), 0, 0);
}
}
Hope this helps! Feel free to ask if you have any questions.
Here’s another solution that works for sufficiently short intervals
(Edit: this limit is due to 32-bit floating point precision, as it’s unwise to accumulate more than 3 digits of integral values, roughly speaking. Obviously, IEEE-754 is a binary format, not decimal, so the explanation is more complicated than that.)
using UnityEngine;
public class RotateOverTime : MonoBehaviour {
[SerializeField] [Range(1E-2f, 480f)] float _duration; // in seconds (assumes one revolution)
[SerializeField] Vector3 _eulerAxis; // in degrees of rotation
float _elapsed = 0f;
Vector3? _rotationAxis;
#if UNITY_EDITOR
void OnValidate() => _rotationAxis = null;
#endif
void Update() {
if(!_rotationAxis.HasValue)
_rotationAxis = Quaternion.Euler(_eulerAxis) * Vector3.right;
var t = _elapsed / _duration;
var angle = Mathf.LerpUnclamped(0f, 360f, t);
transform.localRotation = Quaternion.AngleAxis(angle, _rotationAxis.Value);
_elapsed += Time.deltaTime;
if(_elapsed >= _duration) _elapsed -= _duration;
}
}
Edit: had a typo Validate => OnValidate