- Home /
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
}
}
}
Answer by tormentoarmagedoom · Jun 22, 2018 at 09:04 PM
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
lol, I like using the curly brackets to add a form of separation throughout the script.
Answer by Raimi · Jun 22, 2018 at 09:47 PM
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 :)
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.
Answer by KloverGames · Jun 23, 2018 at 12:05 AM
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
If you need more control you can use...
if(Input.Get$$anonymous$$eyUp())
But with the code above you don't need to do that