0
\$\begingroup\$

In my game i'm using Unity First Person controller. I check every second what I am looking with the following code:

 cam = Camera.main;
 RaycastHit hit;
 Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane));
 if (Physics.Raycast(CameraCenter, transform.forward, out hit, 5))
 {
      WhatIamLookinTag = hit.transform.tag;
 }

The problem is that isn't working if move Up and down player "view" (so i move up and down mouse..)

I need the object that is in screen center (based on what am i looking).

Why ?

\$\endgroup\$
  • 1
    \$\begingroup\$ I notice you're getting the position of the camera from one object (cam), and the direction to fire the ray from what might be another (this.transform) - are these the same object in your example? Can you show us how you've populated the cam variable? \$\endgroup\$ – DMGregory Mar 31 '19 at 17:59
  • \$\begingroup\$ You were right, like all times you help me. Many thanks man ! \$\endgroup\$ – stighy Mar 31 '19 at 18:25
  • 3
    \$\begingroup\$ If you've solved your problem, feel free to post your solution as an answer. \$\endgroup\$ – DMGregory Mar 31 '19 at 18:26
0
\$\begingroup\$

This solved my problem: cam.transform.forward instead transform.forward

cam = Camera.main;
 RaycastHit hit;
 Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane));
 if (Physics.Raycast(CameraCenter, cam.transform.forward, out hit, 5))
 {
      WhatIamLookinTag = hit.transform.tag;
 }

Thanks to DMGregory.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.