Unity—Rigidbody钢体移动时抖动问题

Rigidbody移动时抖动问题

撞墙抖动

Unity中物体移动有非常多的方式;

比如:

transform.position += dir*speed*Time.deltaTime;
transform.Translate(pos, Space.World);

但是这种方式与碰撞结合时,是先位移在判断碰撞,会导致撞墙抖动

而钢体中修改速度,或是添加力,是先判断碰撞在移动,有效解决撞墙抖动问题;

RigidBody rig;
rig.AddForce(dir*speed);

rig.velocity = new Vector3(pos.x, 0, pos.z) * speed * Time.fixedDeltaTime;

众所周知,人物移动时乘以Time.fixedDeltaTime,相当于逻辑在FixedUpade中调用,每间隔0.02s移动一次;

移动抖动

如果你的摄像机跟随人物移动,一般会将摄像机逻辑写在LateUpdate中处理,保证每一帧的最后调用,有效保护游戏的公平性;

但这样钢体移动和摄像机移动不同步,会导致移动时屏幕不断抖动;

所谓这里的摄像机逻辑建议都写在FixedUpdate周期中;

public class CameraController : MonoBehaviour
{
    public Transform hero;
    private float distacne = 6.5f;
    private float height = 6.3f;
    public void FixedUpdate()
    {
        transform.LookAt(hero);
        transform.position = hero.position + new Vector3(distacne,height,0);
    }
}

移动不下落

由于直接修改钢体速度,速度y赋值为0会导致松了移动键物体才会下落,导致悬空走的情况;

解决方式,将钢体速度的y值赋值为-0.3即可,模拟自由落体的重力;

posted @ 2021-10-15 23:09  小紫苏  阅读(2314)  评论(0编辑  收藏  举报