Home > Blockchain >  How to reduce movement speed in one direction 2d unity
How to reduce movement speed in one direction 2d unity

Time:02-21

I am making a game about ships and am trying to lower movement speed when going in reverse. I don't want to disable reverse movement as if a player were to ram against an obstacle, they would have a hard time getting unstuck without reverse, but I still want it to be slow enough that it won't be useful outside of getting unstuck.

public class PlayerMovement : MonoBehaviour
{
    public float RotateSpeed = - 90;
    public float MoveSpeed = 60;
    float rotateinput;
    float moveinput;
    public float reverselimiter = 0.3f;
    Rigidbody2D rigidbody2d;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        rotateinput = Input.GetAxis("Horizontal");
        moveinput = Input.GetAxis("Vertical");
        if(moveinput == -1)
        {
            reverselimiter = 0.3f;
        }
        else
        {
            reverselimiter = 1f;
        }
    }
    private void FixedUpdate()
    {
        rigidbody2d.angularVelocity = rotateinput * RotateSpeed;
            rigidbody2d.velocity = transform.up * moveinput * MoveSpeed * reverselimiter;

        
    }
}

I tried to check if the player was holding the reverse key with an if statement and then changing the reverselimiter variable to 0.3 if it was being held down. This kind of works but takes a second to start working and stops right when the reverse key is no longer held down which means that the ship speeds back up until it runs out of momentum. Any help would be appreciated!

CodePudding user response:

From what I can tell you want it to slow into a stop or just slow down when they are holding in reverse. So, try something like this:

public class PlayerMovement : MonoBehaviour
{
    public float RotateSpeed = - 90;
    public float MoveSpeed = 60;
    float rotateinput;
    float moveinput;
    public float reverselimiter = 0.3f;
    Rigidbody2D rigidbody2d;
    // Start is called before the first frame update
    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        rotateinput = Input.GetAxis("Horizontal");
        moveinput = Input.GetAxis("Vertical");
        if(moveinput == -1)
        {
            if(reverselimiter >= 0){
                  reverselimiter -= reverselimiter * 0.3;
            }
        }
        else
        {
            if(reverse limiter < 1){
               reverselimiter  = 0.3;
            }
            if(reverselimiter >= 1){ reverselimiter = 1;}
        }
    }
    private void FixedUpdate()
    {
        rigidbody2d.angularVelocity = rotateinput * RotateSpeed;
            rigidbody2d.velocity = transform.up * moveinput * MoveSpeed * reverselimiter;

        
    }
}
  • Related