Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private float CalculateBrakeAccel(float targetPos)
- {
- // targetPos has the position in the z axis the object should stop
- // i.e.: velocity is 0.0f
- float remainingDistance = (targetPos - rigidbody.position.z);
- // formula: a = 0.5 * v0^2 / (e0 - e)
- float brake = 0.5f * rigidbody.velocity.sqrMagnitude / remainingDistance;
- return brake;
- }
- public float Accel = 8f;
- private float maxVelocity = 19.44f; // in m/s, approx. 70km/h
- [...]
- void FixedUpdate ()
- {
- Vector3 forwardForce;
- Vector3 projected;
- if (playerController.PowerInput < 0.0f) // if user braking, PowerInput = -1
- {
- float brakeAccel = CalculateBrakeAccel(playerController.BrakeTarget); // BrakeTarget is the transform.position.z where the user pushed the brakes + 10 meters
- forwardForce = new Vector3(0.0f, 0.0f, brakeAccel * playerController.PowerInput);
- Vector3 drag = rigidbody.velocity * Mathf.Clamp01(1f - rigidbody.drag * Time.fixedDeltaTime);
- if (drag.z > 0.0f)
- forwardForce += drag;
- else
- {
- forwardForce -= drag;
- }
- rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
- }
- if (!CapAtMaxSpeed()) // if max. vel not reached, accel force can be applied:
- {
- forwardForce = new Vector3(0.0f, 0.0f, playerController.PowerInput * Accel);
- rigidbody.AddForce(myTransform.TransformDirection(forwardForce));
- }
- }
- bool CapAtMaxSpeed()
- {
- // velocityMagnitude == rigidbody.velocity.magnitude but without sqrt() operation.
- velocityMagnitude = Vector3.Dot(rigidbody.velocity, myTransform.forward);
- if (velocityMagnitude > maxVelocity)
- {
- rigidbody.velocity = rigidbody.velocity.normalized * maxVelocity;
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement