给游戏物体加力(跳跃后的滑动效果)——deltatime相乘导致的抖动问题

问题描述 投票:0回答:1
//inside update method which is called 60/120 times per second
long currentFrameTime = System.nanoTime();
float deltaTime = (currentFrameTime - lastFrameTime) / 1_000_000_000.0f;
lastFrameTime = currentFrameTime;

float nextForceSlide = forceSlide - forceSlideDecreaseRate * deltaTime;
if (nextForceSlide < 0) {
   forceSlide = 0;
} else forceSlide = nextForceSlide;

updatePosition(this, game.joyStick.angle, forceSlide * deltaTime);


//method
public void updatePosition(Entity entity, double angle, float length) {
   entity.position.x = entity.position.x + length * (float) Math.cos(Math.toRadians(angle));
   entity.position.y = entity.position.y + length * (float) Math.sin(Math.toRadians(angle));
}

这就是我尝试向玩家当前所看方向添加一点力的方法。由于我想支持 30 60 120 fps,因此每个施加的力的结果应该相同。但现在当玩家滑动时,感觉很紧张,不顺畅。为什么?

当我的玩家在跳跃动作后滑动时,我尝试给它添加一点力。目前感觉非常紧张。我以为会很顺利。

game-development game-physics game-engine
1个回答
0
投票

发生抖动是因为您在更新位置时应用了

deltaTime
两次。

更新方法

// inside update method which is called 60/120 times per second
long currentFrameTime = System.nanoTime();
float deltaTime = (currentFrameTime - lastFrameTime) / 1_000_000_000.0f;
lastFrameTime = currentFrameTime;

float nextForceSlide = forceSlide - forceSlideDecreaseRate * deltaTime;
if (nextForceSlide < 0) {
    forceSlide = 0;
} else {
    forceSlide = nextForceSlide;
}

// Update the position with forceSlide (not multiplied by deltaTime here)
updatePosition(this, game.joyStick.angle, forceSlide);

更新位置方法

public void updatePosition(Entity entity, double angle, float length) {
    // Multiply by deltaTime here to apply the force over the frame time
    entity.position.x = entity.position.x + length * (float) Math.cos(Math.toRadians(angle)) * deltaTime;
    entity.position.y = entity.position.y + length * (float) Math.sin(Math.toRadians(angle)) * deltaTime;
}

基本上,在

updatePosition
中,应用位置更改时只需乘以
deltaTime
。这样,力就会随着时间的推移而适当缩放,从而避免抖动。现在在不同的帧速率下应该是平滑的。

© www.soinside.com 2019 - 2024. All rights reserved.