How to prevent AddForce from stacking up ?
I have this script for my 2d drone's mouvement using AddForce wich work pretty well, but the problem is that if the player keep pushing the mouvement keys (in one direction), the drone will increase it speed until it becomes uncontrollable and goes way to fast. Could I prevent the forces from stacking up with a "setForce" (I know it doesn't exist) or maybe assign a maximum speed to my rigidbody ?
void FixedUpdate ()
{
ControlDrone();
drone.AddRelativeForce(Vector2.up * rapidité);
drone.AddRelativeForce(Vector2.right * rapidité * direction);
}
void ControlDrone()
{
if (Input.GetAxisRaw("Vertical") > 0f)
{
rapidité = 15f;
}
if (Input.GetAxisRaw("Vertical") < 0f)
{
rapidité = 5f;
}
if (Input.GetAxisRaw("Vertical") == 0f)
{
rapidité = 9.81f;
}
if (Input.GetAxisRaw("Horizontal") > 0f)
{
direction = 1f;
}
if (Input.GetAxisRaw("Horizontal") < 0f)
{
direction = -1f;
}
if (Input.GetAxisRaw("Horizontal") == 0f)
{
direction = 0f;
}
}
Answer by OpenMindStudios · Dec 02, 2017 at 04:40 PM
set a limiter on it.
As I'm not sure what drone is I'm going to assume that it's a GameObject so something like this should work
public GameObject drone; public Rigidbody droneRigidbody; public float maximumSpeed = 0.0f; // Update is called once per frame void ControlDrone () { droneRigidbody = drone.GetComponentInChildren (Rigidbody); if (droneRigidbody.velocity.x < maximumSpeed) { if (droneRigidbody.velocity.y < maximumSpeed { //rest of control drone script } } }
Now this is pretty basic and you can tweak it, if you'd like a maximum combined speed of X and Y you can put them in to one if statement, or you can create individual limits for each axis, also I see you said it's 2D if your using 2DRigidbody you'll have to use the right Rigidbody class, I'm sure this should be enough to help you!