This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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

in Engine by (173 points)

1 Answer

0 votes
Best answer

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()
by (678 points)
selected by

Thanks for the extra information!

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

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.