Search code examples
c#unity-game-enginegame-physicsphysics

sphere cast outputting only the center of the game object


i'm trying to make a aimbot that detects with the sphere cast if it's hitting something i a bigger radius and if the aimbot is on then it shoots the bullet there, but it keeps outputting the middle of the hit gameobject spherecast() it's called in update aim gameobject it's a representation of the position where the bullet should get if the aim is on code:

public void spherecast()
    {
        origin = gunTip.transform.position;
        direction = guntip.transform.forward;
        RaycastHit hit;
        if (Physics.SphereCast(origin,sphereradus, direction,out hit,maxDistance,whatIsenemy))
    {
        Debug.Log("I hit enemy");
        Debug.Log("position" + hit.transform.position);
        aim.transform.position = hit.transform.position;
        currentHitDistance = hit.distance;
    }
    else
    {
        currentHitDistance = maxDistance;
    }
}

Solution

  • Physics.SphereCast outputs nothing like that at all.

    It is you using hit.transform.position which of course is the general pivot point of the hit object.

    SphereCast provides you with a RaycastHit with a lot of additional information like in particular the RaycastHit.point you are looking for!

    public void spherecast()
    {
        origin = gunTip.transform.position;
        direction = guntip.transform.forward;
    
        if (Physics.SphereCast(origin, sphereradus, direction,out var hit, maxDistance, whatIsenemy))
        {
            // By passing in the hit object you can click on the log in the console 
            // and it will highlight the according object in your scene ;)
            Debug.Log($"I hit enemy \"{hit.gameObject}\"", hit.gameObject);
    
            Debug.Log($"hit position: {hit.point}", this);
            aim.transform.position = hit.point;
            currentHitDistance = hit.distance;
        }
        else
        {
            currentHitDistance = maxDistance;
        }
    }