Java 我需要增加蛇的数量';它每次吃东西都会加速

Java 我需要增加蛇的数量';它每次吃东西都会加速,java,class,methods,game-engine,boolean-logic,Java,Class,Methods,Game Engine,Boolean Logic,蛇的速度是用两个值来衡量的,每次它吃东西的时候,我都试图提高它的速度 我已经研究过布尔方法和值,但我找不到正确的逻辑,即应该将值增加到哪个变量,应该减少或保持原样 公开课选手{ 公共公正; 公共计数器; 公共事务经理; 公共玩家(处理者){ this.handler=handler; moveCounter=0; speedManager=5;//每当我增加此值时 //蛇的初始速度变慢了 正义=虚假; } 公共空白勾号(){ moveCounter+=1; 如果(移动计数器>=速度管理器){

蛇的速度是用两个值来衡量的,每次它吃东西的时候,我都试图提高它的速度

我已经研究过布尔方法和值,但我找不到正确的逻辑,即应该将值增加到哪个变量,应该减少或保持原样


公开课选手{
公共公正;
公共计数器;
公共事务经理;
公共玩家(处理者){
this.handler=handler;
moveCounter=0;
speedManager=5;//每当我增加此值时
//蛇的初始速度变慢了
正义=虚假;
}
公共空白勾号(){
moveCounter+=1;
如果(移动计数器>=速度管理器){
选中CollisionAndMove();
moveCounter=0;
}
/*
*在下一个if语句中,我试图增加
*每次使用Eat()方法时snake的速度
*;然而,每当我吃苹果时,蛇总是简单地
*速度非常快,如果我再吃一次,就看不到任何变化。
*/
如果(isJustAte()){
选中CollisionAndMove();
移动计数器+=5;
}
}
公共图书馆{
Setjuste(真);
}
公共布尔值isJustAte(){
回归公正;
}
public void setJustAte(布尔justAte){
this.justAte=justAte;
}
}

在第二个if语句中,我试图给出(justAte=true),但它对蛇的影响是从一开始就非常可笑的速度。

简短回答:将speedManager减少1

但是你只能这样做5次,所以在吃了5种食物后,它的速度是恒定的,相当于每滴答一次。
游戏中的动作要比这复杂一些。如果您可以访问滴答声之间的增量时间(实时测量的滴答声之间的差值),则可以通过使用浮点数更平滑地更改snake的速度。通过这种方式,它不会被整数值严重量化,而是取决于实时性,而不是帧速率

您可以使用每刻度增加一个移动计数器。当它大于/等于
speedManager
时,您可以向前移动。这意味着
speedManager
实际上等于移动之间的刻度数。因此,增加它将增加移动之间的等待时间。如果你想跑得更快,你必须减少等待时间

此外,在您当前的逻辑中,justAte在设置后将始终等于true,在gameTick中,您需要在增加移动速度后将其设置为false,以避免再次增加

按照这种逻辑,你不能超过每滴答一次的移动速度,也不能使用非整数的速度。如果需要更多的预编码移动,则必须将该位置存储为浮点数(尽管显示的是一个四舍五入的整数),并根据时间增加每个刻度的值。大多数游戏引擎都使用一个表示时间流逝量的增量

下面是一个例子,如果你只是以一定的速度沿着一个轴(1D)移动某物,那会是什么样子

private static final int TICKS_PER_SECOND = 60;
private float position = 0.0f;
private float speed = 2.0f; // specified in per second in this case

/**
 * @param delta  the time passed since gameTick was called the last time in seconds (fraction of a second)
 */
public void gameTick(float delta) {
    //update game elements
    position += speed * delta;  // as speed is specified in distance per second we can just multiply it with the time passed (delta in seconds) and add that to the position
}

public void gameLoop() {
    long lastTick = System.currentTimeMillis(); // the time the last tick occured (in milliseconds since 1970)
    while(true) {
        try { Thread.sleep(1000 / TICKS_PER_SECOND); } catch(InterruptedException e) { e.printStackTrace(); } // tick rate will slightly undercut TICKS_PER_SECOND as this wait doesn't correct for processing time
        long deltaMillis = System.currentTimeMillis() - lastTick; // milliseconds passed since the last tick

        //TODO: perform input

        //update
        gameTick((float)deltaMillis / 1000.0f);

        //TODO: render

        lastTick += deltaMillis; // by not using currentTime but the delta that was processed by gameTick, we keep an accurate time (not slowing down the game due to processing time in the gameTick method) 
    }
}