Hey everybody,
Can somebody help out with this bit of code? I’m not sure why it doesn’t work.
I am trying to limit the speed of the rigidbody to 10.
// Trying to Limit Speed
if(rigidbody.velocity.magnitude > 10){
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
print("Why Doesn't this Work?");
}
Why Doesn’t this Work? is showing up in the Console, but my speed is not being limited.
Any help is really appreciated.
Thanks!
Drag this on the cube:
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class NewBehaviourScript : MonoBehaviour {
public float maxSpeed = 10f;
void Update()
{
// Trying to Limit Speed
if(rigidbody.velocity.magnitude > maxSpeed){
rigidbody.velocity = Vector3.ClampMagnitude(rigidbody.velocity, maxSpeed);
}
}
void OnGUI()
{
GUI.Label(new Rect(20, 20, 200, 200), "rigidbody velocity: " + rigidbody.velocity);
}
}
diff.Normalize();
rb2d.AddForce(diff * Aceleracion * Time.fixedDeltaTime);
float speed = Vector3.Magnitude(rb2d.velocity); // test current object speed
if (speed > VelocidadMaxima)
{
float brakeSpeed = speed - VelocidadMaxima; // calculate the speed decrease
Vector3 normalisedVelocity = rb2d.velocity.normalized;
Vector3 brakeVelocity = normalisedVelocity * brakeSpeed; // make the brake Vector3 value
rb2d.AddForce(-brakeVelocity); // apply opposing brake force
}