rigidbody velocity not working

Hello,

I currently have a small Problem with my game. And I really run out of ideas. I traced the problem to the velocity function of a rigid body.
Heres my code

Rigidbody2d  player = GetComponent<Rigidbody2D>();

Update loop:

if (Input.GetMouseButton(0))
            {
              player.velocity = vector2.zero;
}

if (Input.GetMouseButtonUp(0)){
              player.velocity = vector2.zero;
}

The GetMouseButton Function always works. But the GetMouseButtonUp only works sometimes. Both listeners are called just fine. I tested it by writing to the log if a listener was called.
But the velocity doesnt always seems to change.
Has anyone any idea?

Kind regards,
Colin

Hello there,
I know the answer is a bit late, but it propably will help future searchers. :slight_smile:

I think you have to pultiply the vector with a speed value.
Like this:

public float speed = 10f;
Rigidbody2d  rb2d;

void Start()
{
rb2d = GetComponent<RigidBody2D>();
}
 
 void Update ()
 {
 if (Input.GetMouseButton(0))
             {
               player.velocity = vector2.right * speed;
 }
 
 if (Input.GetMouseButtonUp(0)){
               player.velocity = vector2.left * speed;
 }
}

I didnt try it, but it should do something you can work with.

have a nice day,

WbrJr

Use this format instead:

       public float speed = 10f;
       RigidBody2D rb;
       void Start()
       {
              rb = GetComponent<RigidBody2D>();
       }
       void Update
       {
             if(Input.GetMouseButtonDown(0))
             {
                   rb.velocity = new Vector3((speedx * speed), speedy, speedz); 
             }
        }
  • N.B: speedx, speedy and speedz are my own arbitrary values, you can use whatever variable values you want.
    This code can be improved but I’m pretty sure this will solve most of your problems. I hope I helped whoever was struggling with this(I too struggled with this before so I know your pain).

very weird glitch but here is how to fix it
just multiply by 0
rb.velocity = Vector3.zero * 0;
it doesn’t always work, but it makes the glitch A LOT more rare so yeah, hope it helped