- Home /
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
Answer by WbrJr · Dec 05, 2017 at 08:48 PM
Hello there, I know the answer is a bit late, but it propably will help future searchers. :)
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
Answer by Bekatam · May 17, 2020 at 11:18 AM
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).
Answer by ziyadedris · Jun 17, 2021 at 11:15 AM
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
Your answer
Follow this Question
Related Questions
Player parent to platform problem 0 Answers
Android velocity slower than editor 0 Answers
Unity background sound and player controll ? 0 Answers
rigidbody2D.velocity.y always returns 0 2 Answers