Home > OS >  Unity: Why wont my movement return to value 0
Unity: Why wont my movement return to value 0

Time:11-08

Hi im new to programming in C# and i ran into a problem.Eveything is working,only the value wont return to 0 when the button is not pressed,i can change the direction of the movement,but the object wont stop moving...Here is the code!

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

public class Movement : MonoBehaviour
{
    private Rigidbody2D rb2D;
    private float speed = 1f;
    private float moveHorizontal;

    void Start()
    {
         rb2D = GetComponent<Rigidbody2D>();
    }
  
    void Update()
    {
         moveHorizontal = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
        {
            rb2D.AddForce(new Vector2 (moveHorizontal * speed, 0f), ForceMode2D.Impulse);
        }
    }
}

CodePudding user response:

I see you adding forces, but you never reset the velocity to 0 anywhere

you could do this like e.g.

if(Mathf.Abs(moveHorizontal) > 0.1f)
{
    ...
}
else 
{ 
    var vel = rb2D.velocity; 
    vel.x = 0; 
    rb2D.velocity = vel; 
}

CodePudding user response:

You need to look closely to why nothing will happen when you release your keyboard button.

In your Update you set the moveHorizontal indeed to zero, so it has to work.

However in your FixedUpdate you are updating rb2D only when moveHorizontal doen not fall into the range of -0.1f and 1.0f. (Little tip for maintenance, swap the two checks, we are used to read from left to right and from low to high - derHugo has a nice tweak too.)

When the conditions of the if statement are met, you add force. However when not, you do nothing thus the rb2D.velocity stays as it is.

A possible solution could be adding an else and set the velocity there to zero or rebuild the velocity which is needed but without the moveHorizontal modifier.

void Update()
{
     moveHorizontal = Input.GetAxisRaw("Horizontal");
}

void FixedUpdate()
{
    if (moveHorizontal > 0.1f || moveHorizontal < -0.1f)
    {
        rb2D.AddForce(new Vector2 (moveHorizontal * speed, 0f), ForceMode2D.Impulse);
    }

    // Possible solution

    else
    {
        // For setting up and down to zero
        rb2D.velocity = Vector2.zero;
        // or rb2D.velocity = new Vector2(0, rb2D.velocity.y);

    }
}
  • Related