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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question Raycast Very Inaccurate?

Discussion in 'Scripting' started by LeytonViner, Jun 12, 2022.

  1. LeytonViner

    LeytonViner

    Joined:
    Apr 7, 2017
    Posts:
    151
    Hiya, so my project was fine yesterday and I opened it up today and found the raycasts were very inaccurate. If the raycast hit anywhere near the edge of a block (by this i mean anywhere that is not near the center) it will pass right through. I'm also getting weird things like the raycast hitting two objects simultaneously, despite not being anywhere near the conditions that could possibly create that. I don't know what's up. Here's a picture of it in action:
    https://imgur.com/YP0BEyK (Sorry for no embed, forums don't seem to like gifs.)

    For context, Machine(Clone) is the bottom block. Swinger Servo(Clone) is the block that's just out of frame. I don't know what is wrong. The crosshair is clearly on the machine but it's spitting out two. I've made sure it's not accidentally coming out offset or whatnot. I literally have no clue what is wrong.

    If anyone wants to take a look at the code:

    Code (CSharp):
    1. if (Physics.Raycast(cam.transform.position, cam.transform.forward,out RaycastHit hit, 200f, buildLayers))
    2.         {
    3.             //This isn't the issue. If this was a issue the MouseOver wouldn't be set, but it is being set. Just to the wrong thing.
    4.             if (GameUI.instance.UIUnderMouse())
    5.                 return;
    6.             MouseOver = hit.collider.gameObject;
    7.             mouseOverPoint = hit.point;
    8.         }
    9.         else
    10.         {
    11.             MouseOver = null;
    12.         }
     
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    The easiest thing to do will be to use debug draw ray or draw line to visualise exactly where the ray is currently aiming: https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html

    You also say that the gameUI line isnt the issue, but for sanity sake comment that part out & test without it.

    You could also try using: https://docs.unity3d.com/Manual/CameraRays.html as it takes into account the cameras view frustrum, instead of using Input.mousePosition use ViewportToRay & pass in 0.5f, 0.5f for the centre.

    Hopefully this helps your work out your problem.
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,557
    I'll delete your duplicate post for you.