3rd person Camera entering walls

I am making a game where I use a Camera to track the player I used a simple script for it

[SerializeField] private Transform player;
private float speedOfLerp;
void FixedUpdate()
{
    speedOfLerp=(Vector3.Distance(transform.position, player.position));
    Vector3 DirectAngle = Vector3.Lerp(transform.position, player.position, Time.deltaTime* (speedOfLerp/2));
    transform.position = DirectAngle;
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, player.eulerAngles.y ,transform.eulerAngles.z);
}

but when I turn near a wall it enter the wall and renders the scene from inside it
how will i stop it from enetring walls I wan it to be like Minecraft 3rd person camer

I have thought of making a raycast from the player with distance of the camera from the player and placing the camer where it collides but I dont want to waste my time trying :slight_smile:

Yes, that’s how it’s normally done. But move your camera code into LateUpdate and not FixedUpdate. LateUpdate will be updated after Update and so if you move your player in Update then you can be sure the camera will always be updated immediately after the player has moved.

Also, by default FixedUpdate updates at 50hz and so your camera movement won’t be smooth on a display with a refresh rate higher than 50hz.

Ok,but now how will I set the camera position there as ray cast happens in one frame , how do I get the position where it hits.

Are you replying under a new account?

In any case, just use the raycast hit position: Unity - Scripting API: RaycastHit.point

That said, Cinemachine has all these features built in.

1 Like

I beg to differ. :wink:

Normally, we’d use Cinemachine as spiney said because that has built-in collision avoidance with a quality that’s far superior than a single raycast (ie it won’t have the camera slide into a tiny crevice or hole in a wall … we often call them “windows”).

2 Likes

Cinemachine sounds awesome. I’ll have to try it out sometime.