- Home /
 
How can I check when the centre of camera is looking at a gameobject?
how to touch off a event when the centre of camrea look at a gameobject?
Answer by IJM · Oct 11, 2010 at 02:25 AM
I think that best way to do taht is to use raycasting.
Raycast script reference: http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
Use ScreenToWorldPoint function to get the center of the camera. Your argument for ScreenToWorldPoint should be Vector3(Screen.width/2, Screen.heigh/2, camera.nearClipPlane).
ScreenToWorldPoint script reference: http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenToWorldPoint.html
Example: (Attach it to an object that has a camera component)
using UnityEngine; using System.Collections;
 
               public class example : MonoBehaviour { void Update() { Vector3 CameraCenter = camera.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.heigh/2, camera.nearClipPlane)); if (Physics.Raycast(CameraCente, transform.forward, 100)) Debug.Log("Ou yeah!");
 
                }
 
               } 
 
               
               p.s.
I didn't test this code ;)
Thanks, works. However, how can I check wich object I hit? (I hope you're still active on the forum :p)
You can use the hit info.
In the given example, the hit info was not used, but you can add it like this: 
 RaycastHit hit;
 var cameraCenter = camera.ScreenToWorldPoint(new Vector3(Screen.width / 2f, Screen.height / 2f, camera.nearClipPlane));
 if (Physics.Raycast(cameraCenter, this.transform.forward, out hit, 1000))
 {
     var obj = hit.transform.gameObject;
 }
 
                  The "obj" is the object that was hit.
If the code is not attached to your main camera, then use ins$$anonymous$$d of "this.transform.forward" the transform of your main camera "mainCamera.transform.forward".
Greetings Chillersanim
Thank you very much. Im still not 100% familiar with raycasts. Cheers mate.
Answer by Eoku · Oct 31, 2015 at 07:07 AM
As an alternative to the (Admittedly better) method presented above, you could just use the mouse. You would use Cursor.lockState = CursorLockMode.Locked to lock the cursor at the center of the screen and Cursor.visible = false to hide it. Then use any of the OnMouse... commands in MonoBehavior to make the object interactive. I guess this method would only be useful in certain circumstances (like the player picking up and carrying rigidbodies), but still worth a mention.
Your answer
 
             Follow this Question
Related Questions
GameObject Moving Slow when drag with hand 0 Answers
Some GameObjects can't touch !!! 0 Answers
Touch different Gameobjects using camera array and raycast hit 3 Answers
Ray Casting - Trigger function 1 Answer
Getting a camera at runtime 1 Answer