Hi. I added Dying delay with Invoke(“LoadScene”, 3f) and disabling controls in this time.
So everything works fine - constraints working. But if i hit an object and enter Dying state, rocket could rotate in X and Y when falling, ignoring Constraints in Rigidbody. It happens not common, so you can miss it, but if rocket hits multiplie surfaces and may hit some when falling - it happens. Why it happens?
public class Rocket : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody _rigidbody;
private AudioSource _audio;
private float _startVolume = 0.5f;
[SerializeField] private float rscThrustRotate = 100f;
[SerializeField] private float rscThrustThrust = 100f;
enum State
{
Alive,
Dying,
Transcending
}
private State _state = State.Alive;
void OnCollisionEnter(Collision collision)
{
if (_state != State.Alive)
{
return;
}
switch (collision.gameObject.tag)
{
case "Friendly":
break;
case "Finish":
_state = State.Transcending;
Invoke("LoadScene", 3f);
break;
default:
_state = State.Dying;
Invoke("LoadScene2", 3f);
break;
}
}
private void LoadScene2()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
private void LoadScene()
{
SceneManager.LoadScene(1);
}
void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_audio = GetComponent<AudioSource>();
Physics.gravity = new Vector3(0, -10.0F, 0);
}
// Update is called once per frame
void Update()
{
if (_state == State.Alive)
{
Thrust();
Rotate();
}
else
{
StartCoroutine(VolumeFade(_audio, 0f, 0.1f));
}
}
void Rotate()
{
_rigidbody.freezeRotation = true;
float rotationThisFrame = Time.deltaTime * rscThrustRotate;
if (Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.D))
{
}
else if (Input.GetKey(KeyCode.A))
{
transform.Rotate(Vector3.forward * rotationThisFrame);
}
else if (Input.GetKey(KeyCode.D))
{
transform.Rotate(-Vector3.forward * rotationThisFrame);
}
_rigidbody.freezeRotation = false;
}
private void Thrust()
{
float thrustThisFrame = Time.deltaTime * rscThrustThrust;
if (Input.GetKey(KeyCode.W))
{
_rigidbody.AddRelativeForce(Vector3.up * thrustThisFrame);
_audio.volume = _startVolume;
if (!_audio.isPlaying)
{
_audio.Play();
}
}
else
{
StartCoroutine(VolumeFade(_audio, 0f, 0.1f));
}
}
IEnumerator VolumeFade(AudioSource _AudioSource, float _EndVolume, float _FadeLength)
{
float _StartTime = Time.time;
while (Time.time < _StartTime + _FadeLength)
{
float alpha = (_StartTime + _FadeLength - Time.time) / _FadeLength;
// use the square here so that we fade faster and without popping
alpha = alpha * alpha;
_AudioSource.volume = alpha * _startVolume + _EndVolume * (1.0f - alpha);
yield return null;
}
}
}