[Godot 2D] To make a ball to reflect which function can I use?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By arthurZ

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.

:bust_in_silhouette: Reply From: Artium Nihamkin

Use get_collision_normal()

Note this function does not exist in Godot 3.0.

kidscancode | 2018-02-11 23:08

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

Artium Nihamkin | 2018-02-12 20:19

:bust_in_silhouette: Reply From: kidscancode

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)

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).

arthurZ | 2018-02-12 00:39

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.

kidscancode | 2018-02-12 17:11