Ball.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using UnityEngine;
  3. namespace UnityStandardAssets.Vehicles.Ball
  4. {
  5. public class Ball : MonoBehaviour
  6. {
  7. [SerializeField] private float m_MovePower = 5; // The force added to the ball to move it.
  8. [SerializeField] private bool m_UseTorque = true; // Whether or not to use torque to move the ball.
  9. [SerializeField] private float m_MaxAngularVelocity = 25; // The maximum velocity the ball can rotate at.
  10. [SerializeField] private float m_JumpPower = 2; // The force added to the ball when it jumps.
  11. private const float k_GroundRayLength = 1f; // The length of the ray to check if the ball is grounded.
  12. private Rigidbody m_Rigidbody;
  13. private void Start()
  14. {
  15. m_Rigidbody = GetComponent<Rigidbody>();
  16. // Set the maximum angular velocity.
  17. GetComponent<Rigidbody>().maxAngularVelocity = m_MaxAngularVelocity;
  18. }
  19. public void Move(Vector3 moveDirection, bool jump)
  20. {
  21. // If using torque to rotate the ball...
  22. if (m_UseTorque)
  23. {
  24. // ... add torque around the axis defined by the move direction.
  25. m_Rigidbody.AddTorque(new Vector3(moveDirection.z, 0, -moveDirection.x)*m_MovePower);
  26. }
  27. else
  28. {
  29. // Otherwise add force in the move direction.
  30. m_Rigidbody.AddForce(moveDirection*m_MovePower);
  31. }
  32. // If on the ground and jump is pressed...
  33. if (Physics.Raycast(transform.position, -Vector3.up, k_GroundRayLength) && jump)
  34. {
  35. // ... add force in upwards.
  36. m_Rigidbody.AddForce(Vector3.up*m_JumpPower, ForceMode.Impulse);
  37. }
  38. }
  39. }
  40. }