Mr. Randy Tom
Mr. Randy Tom

Reputation: 331

Raycasting from the camera center doesn't work

I'm using the following code to raycast from the center of the camera.

using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))] 
public class CameraPointer : MonoBehaviour {
    private GameObject hitObject = null;
    private Vector3 reticlePosition = Vector3.zero; 
    public Camera mcamera;
    public float Distance = 10f;


    void Update () {
        reticlePosition =  mcamera.transform.position; 


        Ray ray = mcamera.ScreenPointToRay(reticlePosition);
        RaycastHit hit;

    
        if (Physics.Raycast(ray, out hit, Distance)) {
            if (hitObject != hit.transform.gameObject) {

                if (hitObject != null) {
                    hitObject.SendMessage("OnReticleExit", SendMessageOptions.DontRequireReceiver); 
                }
                hitObject = hit.transform.gameObject;
                hitObject.SendMessage("OnReticleEnter", SendMessageOptions.DontRequireReceiver); 
            } else {
                hitObject.SendMessage("OnReticleHover", SendMessageOptions.DontRequireReceiver); 

            }
        } else {

            if (hitObject != null) {
                hitObject.SendMessage("OnReticleExit", SendMessageOptions.DontRequireReceiver); 
            }
            hitObject = null;
        }
    }
}

Unfortunately, it doesn't work at all. It is not hitting any object at all. How can I sort this out?

Upvotes: 1

Views: 1943

Answers (2)

blackTree
blackTree

Reputation: 117

Ray ray = mcamera.ScreenPointToRay(reticlePosition); this function is the wrong approach.

vector3 parameter in screenpoint should be the GameScreen Position(ex:coordinate at screen 1920x1080)

So, you have to use function mcamera.ViewportPointToRay(new Vector3(0.5f,0.5f)); or you can use if (Physics.Raycast(reticlePosition, transform.forward,out hit Distance))...

Upvotes: 2

MikeXrayRomeo
MikeXrayRomeo

Reputation: 11

The reason why this may note be working as you intended is that you're projecting a ray from screen space to world space when you call:

Ray ray = mcamera.ScreenPointToRay(reticlePosition);

See the docs here

So if mcamera is located at the origin, you're Raycasting from the bottom left corner of the screen.

If you want to just cast a ray from the center of the camera's viewport, then something like this would work:

Ray ray = new Ray(mcamera.transform.position, mcamera.transform.forward);

This basically casts a ray along the forward vector of the camera starting at the camera's current position.

Upvotes: 0

Related Questions