Raycast / Mouse events not working at certain camera angle

When changing camera position / angle, some of the objects that I need to interact with do not respond to mouse events and raycasts. What am I doing wrong?
Context:
I have 0 experience in game dev / Unity. This is my first pet project.
I’m creating na MMO / MOBA kind of game. The camera distance / rotation can be changed with A S D W keys.

// Some snippets on camera controlls:
transform.RotateAround(target, Vector3.up, rotateSpeed  * direction);

transform.position += -transform.right * arrowSpeed;
// registering the mouse clicks to interact with objects
void Update()
    {
        if(!player){
            return;
        }
        if(Input.GetKeyDown(KeyCode.Escape))
        {
            escapeMenu.gameObject.SetActive(!escapeMenu.gameObject.activeSelf);
        }

        // if right mouse and object not is UI
        if(Input.GetMouseButtonDown(1) && !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

          
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                Debug.DrawRay(ray.origin, ray.direction, Color.red, 5.0f);

                Interactable interactedObject = hit.collider.GetComponent<Interactable>();
                if(interactedObject != null)
                {
                    // tell the player to interact with object
                    player.objectToInteractWith = interactedObject;
                }
                else
                {
                    // clear objectToInteractWith
                    // so player will stop (trying) walking / interacting
                    player.objectToInteractWith = null;
                    player.move(hit.point);
                }
            }
        }

    }
// On object to interact with
void OnMouseOver()
    {
        Debug.Log("Moused over");
    }

expected behaviour
When changing camera distance / rotation, I expect to be able to click on any interactable object (enemy) and click to attack.

actual behaviour

  • At a certain angle the raycasts wont register hit on object
  • At the same angle, OnMouseOver also does not work register.

I have attached an image and marked with green which were clickable, and red which arent.

Thanks In advance.

It turned out to be something stupid:
I accidently added an invisible sphere somewhere in the sky on the map. The raycast sometimes hit the sphere, thus not reaching where my mouse pointer clicked.

Even though in this particular situation it’s not really applicable, I do want to give a tip to my fellow noobs:
There is a layer called “Ignore Raycast”.

To all the mods: this thread can be closed

3 Likes