When I test it when I stop moving the player will go up and down for no reason
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControll : MonoBehaviour {
float vel = 0;
public GameObject Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//input
if (Input.Get(KeyCode.W)) {
vel += 1;
}
if (Input.GetKey(KeyCode.S))
{
vel -= 1;
}
if (!Input.anyKey &&)
{
vel =- Mathf.Sign(vel);
}
//move
Player.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, vel);
}
}
You’ve got an error at line 27 so this code would not compile as is. You’re missing the rhs of your logic-and operator.
What are you trying to achieve with line 29? Mathf.Sign will return either 1 or -1 and then you are negating that and assigning it to vel.
I’m guessing line 29 is meant to bring vel back to 0 when there are no keys pressed. Did you mean to have -= instead of =- on that line? If that is what you’re trying to do I wouldn’t recommend doing it that way, especially since it will likely jump around a lot when it’s near 0. One alternative would be to do something like
vel = Mathf.Lerp(vel, 0, Time.deltaTime*factor);
If you want your acceleration/deceleration to be more constant, you can do something like
if (vel > 0)
vel = Mathf.Max(0, vel - Time.deltaTime*accel)
else
vel = Mathf.Min(0, vel + Time.deltaTime*accel)
with accel being the (positive) acceleration, which will also make it get to 0 in a more predictable way, rather than waiting for it to reach 0 due to precision problems. Also, you’ll probably want to change if (!Input.anyKey) to something else, perhaps to checking if neither of W or S are pressed, since it would probably be confusing to a user if all other keys stop the deceleration. I’d also suggest storing the Rigidbody2D on line 32 to a variable initialized in Awake or Start, so you won’t need to call GetComponent every frame.