Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug Camera.ScreenPointToRay() mouse position moves towards camera

Discussion in 'Scripting' started by YowaiSenshi, Aug 7, 2023.

  1. YowaiSenshi

    YowaiSenshi

    Joined:
    Mar 29, 2022
    Posts:
    2
    I'm having a problem I have no idea why it's happening. I'm using version 2022.3.2f1 and trying to do a top down shooter. So I get mouse's position but for some reason whenever I move it into certain side it starts to move towards the camera.

    Only this function deals with where red ball looks. How can I stop this from happening?

    Code (CSharp):
    1. [SerializeField] private Vector3 hitPos;
    2.     Camera kamera;
    3.     [SerializeField] private GameObject mousePos;
    4.  
    5. //and this is the function that turns character and moves mousePos object
    6. void Rotation()
    7.     {
    8.         Ray ray = kamera.ScreenPointToRay(Input.mousePosition);
    9.         RaycastHit hit;
    10.  
    11.         if (Physics.Raycast(ray, out hit) )
    12.         {
    13.             hitPos = hit.point;
    14.         }
    15.  
    16.         hitPos.y = hitPos.y + 1.75f;
    17.         Vector3 charLook= hitPos - transform.position;
    18.         transform.LookAt(transform.position + charLook,Vector3.up);
    19.             mousePos.transform.position = hitPos;
    20.     }
    (Don't mind the sounds, I was playing Arknights on the background)
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    510
    Your ray is hitting the sphere which is then told to move to the hit point. This causes it to gradually move closer and closer to the camera. Use layers or disable the collider on the sphere (mousePos).
     
    YowaiSenshi and Bunny83 like this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,495
    Right :) Pretty obvious from the footage. So each frame the sphere moves to the hitpoint on its own surface (+ that 1.75) so the sphere gets closer to the camera. The next frame the sphere is now closer and you hit it again so it moves further up. Once the sphere moved out of the view, the ray again hits the floor, so the sphere is placed down there again and the whole cycle starts over.

    You may want to use either a layer mask to exclude the sphere in the raycast, or remove the collider from that sphere. Though I guess it's just a debug sphere anyways? So just removing it would already solve the problem :)
     
    YowaiSenshi likes this.
  4. YowaiSenshi

    YowaiSenshi

    Joined:
    Mar 29, 2022
    Posts:
    2
    I can't believe it was something this simple... Thank you! I was having nightmares because of this.
     
    Bunny83 and zulo3d like this.