Raycast always giving false positive

I’ve got this code here with a picture. I must be doing something wrong as it is my fist time using raycasting. I keep getting that I have hit the sphere every FixedUpdate(). What am I doing wrong?

public void FixedUpdate()
{
    DrawRayAtMouseLocation(MousePosition());
}

private Vector3 MousePosition()
{
    Vector3 v3;
    v3 = new Vector3(Input.mousePosition.x, Input.mousePosition.y, gameObjectToScreenPoint.z);
    return v3;
}

private void DrawRayAtMouseLocation(Vector3 mouseLocationInScreenPoint)
{
    Vector3 forward = transform.TransformDirection(Vector3.forward) * 1;
    Ray r = _shipControls.camera.ScreenPointToRay(mouseLocationInScreenPoint);
    Debug.DrawRay(r.origin, forward, Color.red);
    if (Physics.Raycast(r.origin, forward))//Did we hit something with our ray?
    {
        Debug.Log(gameObject.name);
    }
}

alt text

If I’m not mistaken, it looks like the only especially confusing part is “r.origin”

You’re firing a raycast forward from your character’s transform (read: Vector3 forward) from the location of the ray’s origin. Presumably, the ray’s origin is the camera’s location, which would place it behind your character (thereby making it rather impressive that it’s not simply hitting the character).

The Ray itself looks good, though, so unless I’m missing something, I don’t see what the problem would be with using

if (Physics.Raycast(r))//Did we hit something with our ray?

instead.

So the Raycast was working correctly but I wasn’t getting the Debug.Log I wanted in my if statement. What I needed to do was get what the RaycastHit and get the name of that game object.

Vector3 forward = transform.TransformDirection(Vector3.forward) * 2;
Ray r = _shipControls.camera.ScreenPointToRay(mouseLocationInScreenPoint);
Debug.DrawRay(r.origin, forward, Color.red);
RaycastHit hit;
if (Physics.Raycast(r.origin, forward, out hit))//Did we hit something with our ray?
{
    Debug.Log(hit.transform.gameObject.name);
}