Trying to find how the 'y' position of a Raycast with ScreenPointToRay is set

Hello, I have a 2d game that is laying down in the x & z. You click and drag a game object across the screen. This work, the only problem I have is, when I get the 'hit.point' the 'y' that gets returns is extremely 'high'. I try and set it manually after but it glitches and jumps back and forth from the 'y' in the hit.point to the 'y' that i set manually. Any help at all would be greatly appreciated. Thanks Fabrizio

function Update ()
{
    if (Input.GetButton("Fire1"))
    {
        var ray: Ray = mCamera.ScreenPointToRay(Input.mousePosition);
        var hit: RaycastHit;

        if (Physics.Raycast(ray, hit))
        {
            if(!rockCreated)
            {
                var rock: GameObject;
                var newPosition = Vector3(hit.point.x, hit.point.y, hit.point.z);
                rock = Instantiate(rockPrefab, newPosition, City.transform.rotation);
                Physics.IgnoreCollision(rock.collider, City.collider);
                currRock = rock;
            }
        }

        if(rockCreated)
        {
            Debug.Log("Y position of Hit" + hit.point.y);

            currRock.transform.position.x = hit.point.x;
            currRock.transform.position.z = hit.point.z;
            //currRock.transform.position.y = hit.point.y;
        }
    }
}

It would help if we could see your ray variables (i.e. start, direction) and possibly have an idea of where your colliders are.

Hi, sorry if i'm not sure exactly what you are referring to. Which 'start,direction' are you referring to? The Rock? Since it is instantiated, the start is where you click? Again, sorry if i don't understand exactly what you are asking. Thanks

1 Answer

1

The if(rockCreated) bit should really be inside the if for the raycast, otherwise you're checking against junk or null values, and setting the x/z every frame the mouse is down

If you do want to set the x/z every frame the mouse is down, regardless of hitting something, then store a vector3 when you hit, and set them using that vector instead - i'd skip using the hit variable for anything outside of the raycast check

Thanks, I tried storing the hit in a Vector3 and it didn't seem to achieve what I was looking for. I think my biggest problem is that when the user clicks on the 'screen', the Y position returned is much higher than I need and that i'm expecting. Unless I misunderstand Raycast. When you click, how is it calculating the Y position (in this case at least)? Is it using the Camera position or something else? If I can figure out how that is calculated, then I can adjust it to where I need it to be, and I think I'll be in good shape. Thanks again for your help.

The Y position should be the y position of whatever the ray hits. If it's hitting something too high, it's possible you've got a collider in the way somewhere

Yup, that was the problem. Thanks so much for your help!