Question by
Phasmagorica · Oct 14, 2016 at 05:55 AM ·
movement script
Why does my character keep moving after I release the input?
here is the script
public class PlayerTestMovement : MonoBehaviour {
public float speed = 3f;
private Rigidbody2D body2d;
public Vector2 maxVelocity = new Vector2 (3, 5);
// Use this for initialization
void Start () {
body2d = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
var forceX = 0f;
var forceY = 0f;
var absVelX = Mathf.Abs (body2d.velocity.x);
if (Input.GetKey ("right")) {
if (absVelX < maxVelocity.x)
forceX = speed;
transform.localScale = new Vector3 (1, 1, 1);
} else if (Input.GetKey ("left")) {
if (absVelX < maxVelocity.x)
forceX = -speed;
transform.localScale = new Vector3 (-1, 1, 1);
}
body2d.AddForce (new Vector2 (forceX, forceY));
}
I'm very inexperienced.
Comment
you want to stop the character when you dont press the key? or you want to make the speed down when you not click any buttons
Answer by Zodiarc · Oct 14, 2016 at 07:20 AM
You're working with velocity not with translation. By pressing your move button you add a force to the character and since you don't apply equal counterforce when you release the button, the character keeps the momentum and keeps moving.