Java LibGDX-增量时间有时会导致精灵在曲线移动时行为怪异
所以我想出了当你有3个点时,如何在曲线上移动物体。 我以如下曲线移动精灵: 以下代码在render方法中,该方法循环每个勾号。Java LibGDX-增量时间有时会导致精灵在曲线移动时行为怪异,java,graphics,libgdx,Java,Graphics,Libgdx,所以我想出了当你有3个点时,如何在曲线上移动物体。 我以如下曲线移动精灵: 以下代码在render方法中,该方法循环每个勾号。 if (ship.isMoving()){ // Normalized direction vector towards target Vector2 dir = ship.getEndPoint().cpy().sub(ship.getLinearVector()).nor(); // Move towards
if (ship.isMoving()){
// Normalized direction vector towards target
Vector2 dir = ship.getEndPoint().cpy().sub(ship.getLinearVector()).nor();
// Move towards target by adding direction vector multiplied by speed and delta time to linearVector
ship.getLinearVector().add(dir.scl(2 * Gdx.graphics.getDeltaTime()));
// calculate step based on progress towards target (0 -> 1)
float step = 1 - (ship.getEndPoint().dst(ship.getLinearVector()) / ship.getDistanceToEndPoint());
if (ship.getCurrentPerformingMove() != MoveType.FORWARD) {
// step on curve (0 -> 1), first bezier point, second bezier point, third bezier point, temporary vector for calculations
Bezier.quadratic(ship.getCurrentAnimationLocation(), step, ship.getStartPoint().cpy(),
ship.getInbetweenPoint().cpy(), ship.getEndPoint().cpy(), new Vector2());
}
else {
Bezier.quadratic(ship.getCurrentAnimationLocation(), step, ship.getStartPoint().cpy(),
new Vector2(ship.getStartPoint().x, ship.getEndPoint().y), ship.getEndPoint().cpy(), new Vector2());
}
// check if the step is reached to the end, and dispose the movement
if (step >= 0.99f) {
ship.setX(ship.getEndPoint().x);
ship.setY(ship.getEndPoint().y);
ship.setMoving(false);
System.out.println("ENDED MOVE AT "+ ship.getX() + " " + ship.getY());
}
else {
// process move
ship.setX(ship.getCurrentAnimationLocation().x);
ship.setY(ship.getCurrentAnimationLocation().y);
}
// tick rotation of the ship image
if (System.currentTimeMillis() - ship.getLastAnimationUpdate() >= Vessel.ROTATION_TICK_DELAY) {
ship.tickRotation();
}
}
当我运行这个时,80%的时间它运行平稳,没有问题,但有时它会运行,只是在两个移动之间有一些奇怪的延迟(如果我先做第一个曲线,然后再做另一个曲线),就像有些可疑的东西,我不明白
我是否使用了错误的增量?正如@Tenfour04对您的问题所做的评论。可能是垃圾收集器启动并造成了延迟。不要在更新/渲染循环内创建新对象
// instance variable tmp
private Vector2 tmp = new Vector2();
// dir is now a reference to tmp no new objects allocated
Vector2 dir = this.tmp.set(ship.getEndPoint()).sub(ship.getLinearVector()).nor();
// the same thing with Bezier.quadratic equation
// only the currentAnimationLocation and tmp will be modified in the method
Bezier.quadratic(
ship.getCurrentAnimationLocation(), step, ship.getStartPoint(),
ship.getInbetweenPoint(), ship.getEndPoint(), this.tmp
);
您正在创建大量垃圾对象。可能是GC。避免在游戏循环中分配新对象。