Okay, so I am currently working on a system where players are able to press a key to perform an action on certain objects. Here is what I’ve made so far. https://gyazo.com/3b17a22281f2fb7fcfb78784b836b240
It works completely fine, but currently when an object is obstructing a part, it still gives you the option to perform the action. Here is what I mean
As you can see you have the option to sit down on the couch even though it’s behind the wall. This is what I want to eliminate.
The best way I could come up with is using ray casting to see what object is in front of the camera. Is there anything more efficient that ray casting which I can use? Because my script will be continuously looping while trying to find the object in view.
I’m still learning about this, but you could use Rays to check if a part isn’t blocking a player and an object that can be interacted with. You would have to check if a player is within a certain range, then if the player is within range, create a ray that will check if the player is in a position/area that is logically correct for the player to interact with that object.
I’m currently on my new PC, so I don’t have my files for Rays yet, but I guess other devs could help based off of what I’ve provided.
Raycasting a couple of times every frame is absolutely no issue, and in my opinion is going to be the most efficient thing you can do do solve your problem.
The best solution is to cast 2 rays: one from the character and one from the camera. That way, if the camera gets temporarily blocked by a random small part, the other ray will know the object is in range, or vice-versa.
Also, the character’s ray should originate from the torso so that the 2 rays wouldn’t overlap in 1st person.
I personally would first check to see if the player is actually inside the room of the object you want to interact with. If they are, I would then cast a ray from the camera to the object (ignoring all walls) and see if there is a direct connection between the two. If there is, I would display the ability to use the action.
The object isn’t determined by the target of the mouse, it’s determined by whatever the camera is looking at currently. So unfortunately, that method wont work.
As @nooneisback said, I made it work like this for compatibility with controllers and mobile devices.