Raycasting from Perspective Camera to a Cursor Object

I need to make a raycast that come from my camera through a cursor object instead of my mouse because I need to be able to control it with my controller

here’s my current code:

Transform selectedObj;
RaycastHit hit;
         
Vector3 target;
target = transform.position - Camera.main.transform.position;

Ray ray = new Ray(secondCam.position, target);

Debug.DrawRay(secondCam.position, target * 10, Color.yellow);

if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
    Debug.DrawRay(secondCam.position, target * 10, Color.green);
    selectedObj = hit.transform;
}

this works as long as my mouse is in a certain z position…
but the problem is that when the camera move along z-axis the raycast doesn’t go through the cursor object anymore…

It looks like this (mouse distance to camera is always the same because its the camera’s child) :

Your directional vector, target as you have called it, is from a different position to your ray.

The direction vector is the main camera to the target not the second camera transform. Should it not betarget = transform.position - secondCam.position;

1 Like

oh yeah i forgot to change that
thanks let me try it