How to implement a switch in 3D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ugly_cat
:warning: Old Version Published before Godot 3 was released.

What would be the best way to implement a lever/switch/button in 3d? I was thinking abstractedly about it and was considering casting a ray from the mouse and if it hit the object within a certain distance then it would trigger a function. Now that I think about it that seems like it’s probably the way to do it…

:bust_in_silhouette: Reply From: CowThing

Yes I would use ray casting to achieve this. There’s a tuorial on ray casting here: http://docs.godotengine.org/en/latest/tutorials/ray-casting.html
And at the bottom there’s a 3D specific section that talks about making a raycast from the camera to the mouse position.

You can even use groups to help with this. Put the button and any other object that can be interacted with in a group named “Interactive” or something like that. Then make sure to give anything in that group a function called “do_press” or something similar.
Then you can check if the object that the ray hits is interactable and trigger like this:

if collider.is_in_group("Interactive"):
    collider.do_press()

Thanks for the extra information!

ugly_cat | 2016-04-04 05:19

I would do something similar, though I would use collider.has_method("interact_on_click") or something similar, instead of is_in_group.

Bojidar Marinov | 2016-04-04 09:27