CarSelfRighting.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using UnityEngine;
  3. namespace UnityStandardAssets.Vehicles.Car
  4. {
  5. public class CarSelfRighting : MonoBehaviour
  6. {
  7. // Automatically put the car the right way up, if it has come to rest upside-down.
  8. [SerializeField] private float m_WaitTime = 3f; // time to wait before self righting
  9. [SerializeField] private float m_VelocityThreshold = 1f; // the velocity below which the car is considered stationary for self-righting
  10. private float m_LastOkTime; // the last time that the car was in an OK state
  11. private Rigidbody m_Rigidbody;
  12. private void Start()
  13. {
  14. m_Rigidbody = GetComponent<Rigidbody>();
  15. }
  16. private void Update()
  17. {
  18. // is the car is the right way up
  19. if (transform.up.y > 0f || m_Rigidbody.velocity.magnitude > m_VelocityThreshold)
  20. {
  21. m_LastOkTime = Time.time;
  22. }
  23. if (Time.time > m_LastOkTime + m_WaitTime)
  24. {
  25. RightCar();
  26. }
  27. }
  28. // put the car back the right way up:
  29. private void RightCar()
  30. {
  31. // set the correct orientation for the car, and lift it off the ground a little
  32. transform.position += Vector3.up;
  33. transform.rotation = Quaternion.LookRotation(transform.forward);
  34. }
  35. }
  36. }