0 votes

basically, I am trying to make a ball to reflect after it collides with a "wall" or another balls, similar with a snooker game. I want to know if it is better to use the move_and_slide() or the move_and_collide() functions to do this and why.

I need the normal of the wall to create this?

Thank you.

in Engine by (179 points)

2 Answers

0 votes
by (264 points)

Note this function does not exist in Godot 3.0.

Yep, did not notice the tag. Anyway, your answer is much better :)

+8 votes

If you don't need the slide response (which you don't if you're bouncing), you probably want to use move_and_collide(), which will allow you to reflect the remaining motion vector as well as your velocity vector (to conserve energy).

func _physics_process(delta):
    var collision = move_and_collide(velocity * delta)
    if collision:
        var motion = collision.remainder.bounce(collision.normal)
        velocity = velocity.bounce(collide.normal)
by (21,539 points)

Thank you man. After you posted it I found this in the docs too. I'm studying your 'Godot 101 - Part 13' and trying to port this to godot 3. Your tutorials are so good, you have a great didactic.

Can you explain this line?
'var motion = collision.remainder.bounce(collision.normal)'

Will this pick up the remainder and bounce the ball at the same angle?

I know that some calculation were done automatically and the collision variable has all the information of the collision, but I don't exactly understand what this line is saying in GDscript too (maybe this is the only problem).

Let's break it down:

  • collision.remainder is a vector representing the motion that was incomplete due to the collision. For example, if your velocity was set to move you 100 pixels, but you hit something after moving 75 pixels, remainder would have a length of 25.

  • collision.normal is the normal vector at the point of collision, ie the direction the collision surface is facing.

  • bounce() is a Vector2 method that reflects a vector by a given normal

Combining them all together, we are reflecting the remainder off the collision surface. After that, you should move by that amount, so you don't lose those extra 25 pixels of velocity.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.