Topic was automatically imported from the old Question2Answer platform.
Asked By
aya9
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
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().
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()
aya9 | 2020-12-28 11:09
The collision normal after function to_local() had to be normalized again (at least that is what debugger suggested), but still no joy. Screen
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()
Really, this has saved my day.
Many, many thanks!
zeitgeist | 2021-11-21 22:16
You’re very welcome. Nice to know my answer could actually be helpful to someone.