- Home /
How to trigger scripts with line sight. (3D & First-Person)
As of now, I'm able to pick up items with a spherical collider that is on trigger. I wonder if it's possible that I can also check if my character's facing the item before the character can actually pick it up.
I tried looking up onto it and saw something about "Raycast" or if that's what it's called. I wanted to ask first what would be the best approach to do.
Thanks in advanced guys! :)
Yeah. Use Physics.Raycast to cast a ray towards the camera's transform.forward vector and check if the required script is on the hit object.
The User manual and Scripting API is you friend, as usual :)
Answer by CarterG81 · Feb 11, 2017 at 03:27 PM
Likely you will need to use a raycast, sort through what was hit, and base your code on the result.
Raycast hits = Physics.RaycastAll () //from camera to object (forward)
foreach (Raycast hit in hits)
{
if (hit.gameobject.tag == "Item") //or layer
{
hot.gameobject.GetComponent <ScriptTriggerScript >().EnableMyTriggerScript ();
}
}
public void EnableMyTriggerScript ()
{
myScript.SetActive (true);
}
This is just an example. You could find only the nearest object, the furthest, the first hit, the last hit, all hit (store the hits, then iterate through that list to do logic).
And you dont necessarily need a function like EnableMyTrugherScript. If all gameobjects tagged "Item" used the same scripts, or all gameobjects used a specific script, you could handle it that way.
The idea is...
Check what colliders are infront of the camera. (Center of camera)
Make sure youre hitting the correct objects, for example not the ground collider or uninteractable object.
Once you find the object, do some logic. i.e. Disable the script.
Your answer
Follow this Question
Related Questions
Physics based player controller problems 1 Answer
How to move the rotation of the X and Z axis of a 3D model's head with Mouse Input? 0 Answers
Touch to move 3 Answers
Trigger and raycast error? 2 Answers