首页 > 解决方案 > Camera Follow Causing Player To Stutter Unity 2D

问题描述

I'm currently trying to make the camera follow the player smoothly. The script works fine but the problem is that this script is causing the player to stutter at a certain point. For example, if the player is at X:3, the player would stutter but then if the player was at X:-6, the player would stop stuttering. I'm 100% sure that this script is the problem because if I remove the script, the player stops stuttering.

Here is the camera follow script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollowing : MonoBehaviour
{
    [SerializeField]
    private Transform target;

    [SerializeField]
    private Vector3 cameraOffset;

    [SerializeField]
    private float followSpeed = 10f;

    [SerializeField]
    private float xMin = 0f;

    private Vector3 velocity = Vector3.zero;

    private void FixedUpdate()
    {
        Vector3 targetPos = target.position + cameraOffset;
        Vector3 clampedPos = new Vector3(Mathf.Clamp(targetPos.x, xMin, float.MaxValue), targetPos.y, targetPos.z);
        Vector3 smoothPos = Vector3.SmoothDamp(transform.position, clampedPos, ref velocity, followSpeed * Time.fixedDeltaTime);

        transform.position = smoothPos;
    }
}

If you know the answer or possible causes please tell me, I'm trying to release, publish, etc, this game by the end of this year. Thanks! :D

标签: c#unity3d

解决方案


By stutter I think you mean shake or tremble (not familiar with the stutter word). I would try to adjust to the docs example. Use void Update() or LateUpdate() instead of FixedUpdate().

You may want to use void LateUpdate() if you want your game to be accurate. This method will be called after the input is detected, so it will react better. I believe that this is the better choice, because it will be more accurate than Update().

I would also keep track of where in the scene the shake starts if its from a determined point on, and check for some misplaced collider near the position where the undesired shake starts.


推荐阅读