Camera collision using raycasts (problems with SmoothDamp)

void WallDetection()
{
float wallBuffer = 2f;

    if (Physics.Raycast(TargetLookAt.position, -transform.TransformDirection(Vector3.forward), out hitInfo, Distance, walls))
    {
        Distance = hitInfo.distance - wallBuffer;
    }
}

I have a functional Raycast solution in my camera code that tracks wall collisions and adjusts the camera relative to the player, except the camera code I have is built off code that has built in smoothing into the distance calculation, and it’s making my raycast “bounce” off colliders and messing up the raycast check.


void CalculateDesiredPosition()
{
    // Evaluate distance
    Distance = Mathf.SmoothDamp(Distance, desiredDistance, ref velDistance, DistanceSmooth);

    // Calculate desired position
    desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
}

Vector3 CalculatePosition(float rotationX, float rotationY, float distance)
{
    Vector3 direction = new Vector3(0, 0, -distance);
    Quaternion rotation = Quaternion.Euler(rotationX, rotationY, 0f);
    return TargetLookAt.position + rotation * direction;
}

void UpdatePosition()
{

    var posX = Mathf.SmoothDamp(position.x, desiredPosition.x, ref velX, X_Smooth);
    var posY = Mathf.SmoothDamp(position.y, desiredPosition.y, ref velY, Y_Smooth);
    var posZ = Mathf.SmoothDamp(position.z, desiredPosition.z, ref velZ, X_Smooth);
    position = new Vector3(posX, posY, posZ);

    transform.position = position;

    transform.LookAt(TargetLookAt);
}

The issue in question - I’m a novice coder so I’m probably missing something obvious. I’d like it to either make it perform the same task without the smoothing issue, or preferably modify the Raycast code so that it takes the smoothing in mind when calculating collisions.


Any help is appreciated

After some trial and error I managed to make it functional for my own purposes. - I had overthought this problem severely and could, instead of using a SmoothDamp, smooth the distance with a simple Lerp.


    void CalculateDesiredPosition()
    {
        // Evaluate distance
        Distance = Mathf.Lerp(Distance, desiredDistance, DistanceSmooth * Time.deltaTime);

        // Calculate desired position
        desiredPosition = CalculatePosition(mouseY, mouseX, Distance);
    }

And modified my Raycast code slightly, as I found no wall clipping issue using a Lerp and the extra unit made the camera spin wildly as I got close to the wall.


    void WallDetection()
    {    
        if (Physics.Raycast(TargetLookAt.position, -transform.TransformDirection(Vector3.forward), out hitInfo, desiredDistance, walls))
        {
            Distance = hitInfo.distance;
        }
        else
        {
            Distance = desiredDistance;
        }
    }