有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java队列移动到多个点是不准确的

我创建了一种方法,可以将精灵以恒定速度向任何方向移动到某个点。然后,我为每个要移动的点添加了一个排队系统

我的问题是,如果一个点排队,通常只有第一次移动是正确的,那么精灵似乎会移动到其他点的随机位置奇怪的部分是如果我添加一个

if((int) x != (int) moveInfo.getTargetX() && (int) y != moveInfo.getTargetY()){
    ...
}else{
    this.setPosition(moveInfo.getTargetX(), moveInfo.getTargetY());
    ...
}

精灵完成移动到其随机点后,会将自身校正到其目标位置。我创建了一个调试器,它也不是精灵图像偏移,因为x和y值是真实的

下面是我创建的一些代码,可能导致问题

x and y are doubles.

移动到点队列构造函数:

Queue<MoveInfo> moveTo = new LinkedList<MoveInfo>();

移动到课堂上

private class MoveInfo{

    private double targetX, targetY;
    private double deltaX, deltaY;
    private double direction;
    private double speed;
    private boolean ai;

    public MoveInfo(double targetX, double targetY, double speed){
        this.targetX = targetX;
        this.targetY = targetY;
        this.speed = speed;
        this.deltaX = targetX - x;
        this.deltaY = targetY - y;
        calculateDirection();
        ai = false;
    }

    public void calculateDirection(){
        this.direction = Math.atan2(deltaX, deltaY);
    }

    ... //Setters and getters.
}

调用每个游戏更新:

private void moveToUpdate(){
    if(!spriteMoving && !moveTo.isEmpty()){
        if(!moveTo.peek().isAi()){
            moveInfo = moveTo.poll();
            spriteMoving = true;
            System.out.println("Next X"+moveInfo.targetX+" Y"+moveInfo.targetY);
        }
    }else if(spriteMoving && moveInfo != null){
        if((int) x != (int) moveInfo.getTargetX() && (int) y != moveInfo.getTargetY()){
            double nextY = y + (moveInfo.getSpeed() * Math.cos(moveInfo.getDirection()));
            double nextX = x + (moveInfo.getSpeed() * Math.sin(moveInfo.getDirection()));
            setPosition(nextX, nextY);
        }else{
            this.setPosition(moveInfo.getTargetX(), moveInfo.getTargetY());
            spriteMoving = false;
            moveInfo = null;
        }
    }
}

如果您希望看到代码的其他部分,请在注释中告诉我


共 (0) 个答案