Home > Net >  How to make raycasting very accurate?
How to make raycasting very accurate?

Time:06-21

I'm using raycast to detect the object the player is looking at so it can be picked up. However, it is not very accurate. in my game all small objects are pickable. I'm facing a problem when trying to pick up an item next to many other pickable items because when I'm looking directly at one item and click the pick-up button, it picks another near item instead of the one I'm currently looking at.

        raycastPos = mainCamera.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, 0));
                RaycastHit hit;
                if (Physics.SphereCast(raycastPos, sphereCastRadius, mainCamera.transform.forward, out hit, maxDistance, 1 << interactableLayerIndex))
                {
                    lookObject = hit.collider.transform.gameObject;
                }
                else
                {
                    lookObject = null;
        }  
    
    
     if (PickingUp)
            {
                if (currentlyPickedUpObject == null)
                {
                    if (lookObject != null)
                    {
                        
                        PickupObject();
                        if (lookObject.CompareTag("TargetObj") && !targetObjectsList.Contains(lookObject.gameObject))
                        {
                            if (aSource)
                            {
                                aSource.Play();
                            }
                            targetObjectsList.Add(lookObject.gameObject); 
                            if (targetObjectsList.Count == targetObjects.Length)
                            {
    //
                            }
    
    
    
                        }
                        CenterIcon.SetActive(false);
                    }
    
                }
                else
                {
                   // pickupRB.transform.position = PickupParent.position;
                    BreakConnection();
}

How can I make the raycasting very accurate so only the object I'm pointing to gets picked?

CodePudding user response:

Spherecaat/boxcast cover an area which can be great for small objects as the user does not have to be pixel perfect to click on them especially bid they have a mesh collider such as a key. However. If you have many objects near each other a wider cast can mean other objects are picked up first. Decreasing the radius so only 1 object is covered is one way or using a normal raycast will be more accurate at the expense of needing to be more accurately over said item

  • Related