0 votes

Hi,

I've got a player with raycast2d (laser2d) and where it's ray collides with level walls I'm dynamically positioning another raycast2d (bounce_one), and want the new one to be casting as if it was a reflection of the first one from the wall (see image below). I can position it in the right place, I just can't seem to get it to face where it should. I would greatly appreciate any advice.

Script sits on players node.

if laser2d.is_colliding():
    var laser_coll_point = to_local(laser2d.get_collision_point())
    var laser_coll_normal = to_local(laser2d.get_collision_normal())
    bounce_one.position = laser_coll_point
    var reflection = (laser_coll_point - 
    to_local(laser2d.position)).reflect(laser_coll_normal)
    var angle = laser_coll_point.angle_to_point(reflection)
    bounce_one.rotation = rotation + angle

Screen link

Godot version 3.2.3
in Engine by (21 points)
edited by

2 Answers

0 votes

You can get a forward Vector2 for your original Raycast with Vector2(1 0).rotated(laser.rotation). Once you got that, you can bounce it with the normal v2.bounce(normal). Finally, you go back to a rotation with angle().

by (2,446 points)

Hi @Lopy, thank you for the answer. I've tried your suggestion, but now the second raycast2d is pointing straight back at the first one.

    var laser_coll_point = to_local(laser2d.get_collision_point())
    var laser_coll_normal = to_local(laser2d.get_collision_normal())
    bounce_one.position = laser_coll_point
    var forward = Vector2(1,0).rotated(laser2d.rotation)
    var bounce = forward.bounce(laser_coll_normal)
    bounce_one.rotation = bounce.angle()

The collision normal after function to_local() had to be normalized again (at least that is what debugger suggested), but still no joy. Screen

+1 vote

The biggest problem seemed to be using local coordinates and not global ones. Also it's either using bounce() or negating reflect(). Code that worked is attached below.

var laser_coll_point = laser2d.get_collision_point()
var laser_coll_normal = laser2d.get_collision_normal()
bounce_one.global_position = laser_coll_point
var forward = laser_coll_point - laser2d.global_position
var reflection = -forward.reflect(laser_coll_normal)
bounce_one.global_rotation = reflection.angle()
by (21 points)

Really, this has saved my day.

Many, many thanks!

You're very welcome. Nice to know my answer could actually be helpful to someone. :)

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 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 webmaster@godotengine.org with your username.