How would I counteract the force of the velocity and set it to zero after the input has stopped?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

public Rigidbody Player;

// Update is called once per frame
void FixedUpdate () {
	{
		if (Input.GetKey (KeyCode.UpArrow))
			Player.AddForce (0, 0, 50 * Time.deltaTime);
		else

	}

	{
		if (Input.GetKey (KeyCode.DownArrow))
			Player.AddForce (0, 0, -50 * Time.deltaTime);
		else
			
	}
}

}

Good day.

You only need to set the velocity to 0

Player.velocity = Vector3.zero;

But this code… ITs burning my eyes…
all this { }…

Bye

This is what I could come up with off the top of my head (needs testing)…

void FixedUpdate()
{
    bool buttonActive = false;

    if(Input.GetKey (KeyCode.UpArrow))
    {
         buttonActive = true;
         //Add Force
    }
    //Not using else because both up and down can be true during the frame
    if(Input.GetKey (KeyCode.DownArrow))
    {
         buttonActive = true;
         //Add Force
    }

    //If neither button is being pressed buttonActive will remain false
    if(!buttonActive)
    {
         rigidBody.velocity = new Vector3(0,0,0);   //Stop object
    }
}

There is probable a better way to do it, but hope it helps :slight_smile:


Extra: When adding force in FixedUpdate you don’t need Time.deltaTime as it runs at a fixed rate. You need to use Time.deltaTime in Update when adding force, or your forces will be different across different size devices.

Also Input should be in Update, so you may want to switch from FixedUpdate to Update and use Time.deltaTime on your forces.

I was just having trouble on the else part, what do I put when I want to check for non-input “when the player is not pressing a button”. Else didn’t seem to work so I guess I could use a boolean. Lets see how that works @Raimi