修复物理抖动
初级 程序员
Warning
Bullet Physics is being phased out. We no longer plan to support or expand its features as our focus shifts to Bepu Physics. We recommend transitioning to Bepu Physics for access to the latest updates and ongoing improvements.
在 Stride 中,附加到物理实体上的实体没有应用任何默认平滑处理。这会导致明显的抖动,尤其是当摄像机附加到角色组件上时。
在本教程中,我们将探讨如何使用 SyncScript 为实体添加平滑处理。
Note
你也可以在物理设置配置中减小 FixedTimeStep,以实现更精确的物理模拟。例如,将其从 0.016667 改为 0.008 会提高精度,但代价是更高的 CPU 使用率。
处理两个实体之间平滑的代码
以下代码足以平滑地附加两个实体。请确保对你要平滑的实体解除父子关系,否则 transform 处理器会覆盖此脚本。
[ComponentCategory("Utils")]
[DataContract("SmoothFollowAndRotate")]
public class SmoothFollowAndRotate : SyncScript
{
public Entity EntityToFollow { get; set; }
public float Speed { get; set; } = 1;
public override void Update()
{
var deltaTime = (float)Game.UpdateTime.Elapsed.TotalSeconds;
var currentPosition = Entity.Transform.Position;
var currentRotation = Entity.Transform.Rotation;
var lerpSpeed = 1f - MathF.Exp(-Speed * deltaTime);
EntityToFollow.Transform.GetWorldTransformation(out var otherPosition, out var otherRotation, out var _);
var newPosition = Vector3.Lerp(currentPosition, otherPosition, lerpSpeed);
Entity.Transform.Position = newPosition;
Quaternion.Slerp(ref currentRotation, ref otherRotation, lerpSpeed, out var newRotation);
Entity.Transform.Rotation = newRotation;
}
}
用法示例
此示例演示了对第一人称射击(First Person Shooter) 模板的修改,以集成平滑的摄像机移动。
- 将摄像机从物理实体上分离。
- 从摄像机上移除 FPS 摄像机脚本。
- 创建一个新实体作为角色刚体的子实体。
- 将 FPS 脚本添加到新实体上。
- 调整任何直接引用
CameraComponent的代码,以反映这些更改。
PlayerInput.cs
将
public CameraComponent Camera { get; set; }
改为
public Entity Camera { get; set; }
Utils.cs
将
CameraComponent camera
改为
Entity camera,
并将
camera.Update();
var inverseView = Matrix.Invert(camera.ViewMatrix);
改为
var inverseView = camera.Transform.WorldMatrix;
FpsCamera.cs
删除
/// <summary>
/// Gets the camera component used to visualized the scene.
/// </summary>
private Entity Component;
并将
private void UpdateViewMatrix()
{
var camera = Component;
if (camera == null) return;
var rotation = Quaternion.RotationYawPitchRoll(Yaw, Pitch0);
Entity.Transform.Rotation = rotation;
}
改为
private void UpdateViewMatrix()
{
var rotation = Quaternion.RotationYawPitchRoll(Yaw, Pitch, 0);
Entity.Transform.Rotation = rotation;
}
这就足以看到平滑效果的前后对比了。如果你需要查找有关此问题的更多信息,可以在 Stride GitHub 上找到原始问题。