Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. private float CalculateBrakeAccel(float targetPos)
  2. {
  3. // targetPos has the position in the z axis the object should stop
  4. // i.e.: velocity is 0.0f
  5. float remainingDistance = (targetPos - rigidbody.position.z);
  6. // formula: a = 0.5 * v0^2 / (e0 - e)
  7. float brake = 0.5f * rigidbody.velocity.sqrMagnitude / remainingDistance;
  8. return brake;
  9. }
  10.  
  11. public float Accel = 8f;
  12. private float maxVelocity = 19.44f; // in m/s, approx. 70km/h
  13. [...]
  14. void FixedUpdate ()
  15. {
  16. Vector3 forwardForce;
  17. Vector3 projected;
  18. if (playerController.PowerInput < 0.0f) // if user braking, PowerInput = -1
  19. {
  20. float brakeAccel = CalculateBrakeAccel(playerController.BrakeTarget); // BrakeTarget is the transform.position.z where the user pushed the brakes + 10 meters
  21. forwardForce = new Vector3(0.0f, 0.0f, brakeAccel * playerController.PowerInput);
  22. Vector3 drag = rigidbody.velocity * Mathf.Clamp01(1f - rigidbody.drag * Time.fixedDeltaTime);
  23. if (drag.z > 0.0f)
  24. forwardForce += drag;
  25. else
  26. {
  27. forwardForce -= drag;
  28. }
  29. rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
  30. }
  31. if (!CapAtMaxSpeed()) // if max. vel not reached, accel force can be applied:
  32. {
  33. forwardForce = new Vector3(0.0f, 0.0f, playerController.PowerInput * Accel);
  34. rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
  35. }
  36. }
  37.  
  38. bool CapAtMaxSpeed()
  39. {
  40. // velocityMagnitude == rigidbody.velocity.magnitude but without sqrt() operation.
  41. velocityMagnitude = Vector3.Dot(rigidbody.velocity, myTransform.forward);
  42. if (velocityMagnitude > maxVelocity)
  43. {
  44. rigidbody.velocity = rigidbody.velocity.normalized * maxVelocity;
  45. return true;
  46. }
  47. return false;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement