How to stop the character moving after the button is pressed, using Rigidbody2D()..AddForce?
Hi guys,
I'm currently making a top-down game that has the player character using physics (Rigidbody2D().AddForce)
You move the player using the WASD keys, however the character keeps moving forward. I want it to stop moving once the button is released. I'm still quite new to C# so some help would be very appreciated. Thanks again :)
Here's my code;
public class PlayerMovement2 : MonoBehaviour {
public float speed;
// Update is called once per frame
void FixedUpdate () {
if (Input.GetKey (KeyCode.D)) {
GetComponent<Rigidbody2D>().AddForce (Vector2.right * speed);
}
if (Input.GetKey (KeyCode.A)) {
GetComponent<Rigidbody2D>().AddForce (Vector2.left * speed);
}
if (Input.GetKey (KeyCode.W)) {
GetComponent<Rigidbody2D>().AddForce (Vector2.up * speed);
}
if (Input.GetKey (KeyCode.S)) {
GetComponent<Rigidbody2D>().AddForce (Vector2.down * speed);
}
}
}
Answer by LazyElephant · Mar 18, 2016 at 05:22 AM
First, in a script like this which will be called frequently, it's good practice to cache your Rigidbody2D in your class so you don't have to call GetComponent so often. In a small game it probably won't make a noticeable difference, but if you do it frequently in all of your scripts, the wasted time can add up. You would do this by adding the following lines to your class.
public class PlayerMovement2: MonoBehaviour {
public float speed;
Rigidbody2D rbody;
void Awake() {
rbody = GetComponent<Rigidbody2D>();
}
//...
}
As for stopping the player, you could move using the rigidbody's velocity instead of AddForce.
public class PlayerMovement2: MonoBehaviour {
public float speed;
Rigidbody2d rbody;
void Awake() {
rbody = GetComponent<Rigidbody2d>();
}
void FixedUpdate() {
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
rbody.velocity = new Vector2(x*speed, y*speed);
}
}
If the player doesn't stop quickly enough using GetAxis, you can go to Edit->Project Settings->Input and change the Gravity under the Horizontal and Vertical axes. The higher the number, the faster the axis will go back to 0 after you let go of the movement key.
If this is what you wanted, please accept it as the correct answer by clicking the checkmark
Thank you very much, it worked. In my case I'm also using AddForce to move the object back and forward faster.
float x = Input.GetAxis("Horizontal"); Vector2 vector = new Vector2(x, 0); rb.AddForce(vector force); rb.velocity = new Vector2(x velocity, 0);