Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
3.0 KiB

  1. namespace VRTK.Examples
  2. {
  3. using UnityEngine;
  4. public class RC_Car : MonoBehaviour
  5. {
  6. public float maxAcceleration = 3f;
  7. public float jumpPower = 10f;
  8. private float acceleration = 0.05f;
  9. private float movementSpeed = 0f;
  10. private float rotationSpeed = 180f;
  11. private bool isJumping = false;
  12. private Vector2 touchAxis;
  13. private float triggerAxis;
  14. private Rigidbody rb;
  15. private Vector3 defaultPosition;
  16. private Quaternion defaultRotation;
  17. public void SetTouchAxis(Vector2 data)
  18. {
  19. touchAxis = data;
  20. }
  21. public void SetTriggerAxis(float data)
  22. {
  23. triggerAxis = data;
  24. }
  25. public void ResetCar()
  26. {
  27. transform.position = defaultPosition;
  28. transform.rotation = defaultRotation;
  29. }
  30. private void Awake()
  31. {
  32. rb = GetComponent<Rigidbody>();
  33. defaultPosition = transform.position;
  34. defaultRotation = transform.rotation;
  35. }
  36. private void FixedUpdate()
  37. {
  38. if (isJumping)
  39. {
  40. touchAxis.x = 0f;
  41. }
  42. CalculateSpeed();
  43. Move();
  44. Turn();
  45. Jump();
  46. }
  47. private void CalculateSpeed()
  48. {
  49. if (touchAxis.y != 0f)
  50. {
  51. movementSpeed += (acceleration * touchAxis.y);
  52. movementSpeed = Mathf.Clamp(movementSpeed, -maxAcceleration, maxAcceleration);
  53. }
  54. else
  55. {
  56. Decelerate();
  57. }
  58. }
  59. private void Decelerate()
  60. {
  61. if (movementSpeed > 0)
  62. {
  63. movementSpeed -= Mathf.Lerp(acceleration, maxAcceleration, 0f);
  64. }
  65. else if (movementSpeed < 0)
  66. {
  67. movementSpeed += Mathf.Lerp(acceleration, -maxAcceleration, 0f);
  68. }
  69. else
  70. {
  71. movementSpeed = 0;
  72. }
  73. }
  74. private void Move()
  75. {
  76. Vector3 movement = transform.forward * movementSpeed * Time.deltaTime;
  77. rb.MovePosition(rb.position + movement);
  78. }
  79. private void Turn()
  80. {
  81. float turn = touchAxis.x * rotationSpeed * Time.deltaTime;
  82. Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
  83. rb.MoveRotation(rb.rotation * turnRotation);
  84. }
  85. private void Jump()
  86. {
  87. if (!isJumping && triggerAxis > 0)
  88. {
  89. float jumpHeight = (triggerAxis * jumpPower);
  90. rb.AddRelativeForce(Vector3.up * jumpHeight);
  91. triggerAxis = 0f;
  92. }
  93. }
  94. private void OnTriggerStay(Collider collider)
  95. {
  96. isJumping = false;
  97. }
  98. private void OnTriggerExit(Collider collider)
  99. {
  100. isJumping = true;
  101. }
  102. }
  103. }