将速度应用于无与伦比的AI桨,以进行简单的乒乓球游戏



我已经在Android Studio上为大学课程创建了一个简单的乒乓球游戏。在这一点上,几乎一切都准备就绪,除了我为敌人桨创建了无与伦比的AI。我用默认的RectF类创建了桨和球,并根据球的当前位置更改AI桨的位置(我减去/添加65,因为我的桨的长度为130像素,并且与球相比,它将桨叶居中(。从本质上讲,这使敌方桨可以以无限的速度移动,因为它与球的速度/位置匹配(球速度随每个新水平的增加(。这是该方法:

public void AI(Paddle paddle) {
    RectF paddleRect = paddle.getRect();
    RectF ballRect = ball.getRect();
    if (ballRect.left >= 65  && ballRect.right <= screenX - 65) {
        paddleRect.left = (ballRect.left - 65);
        paddleRect.right = (ballRect.right + 65);
    }
    if (ballRect.left < 65) {
        paddleRect.left = 0;
        paddleRect.right = 130;
    }
    if (ballRect.right > screenX - 65) {
        paddleRect.left = screenX - 130;
        paddleRect.right = screenX;
    }
}

供参考,这是我的Paddle类的相关部分:

public Paddle(float screenX, float screenY, float xPos, float yPos, int defaultSpeed){
    length = 130;
    height = 30;
    paddleSpeed = defaultSpeed;
    // Start paddle in the center of the screen
    x = (screenX / 2) - 65;
    xBound = screenX;
    // Create the rectangle
    rect = new RectF(x, yPos, x + length, yPos + height);
}
// Set the movement of the paddle if it is going left, right or nowhere
public void setMovementState(int state) {
    paddleMoving = state;
}
// Updates paddles' position
public void update(long fps){
    if(x > 0 && paddleMoving == LEFT){
        x = x - (paddleSpeed / fps);
    }
    if(x < (xBound - 130) && paddleMoving == RIGHT){
        x = x + (paddleSpeed / fps);
    }
    rect.left = x;
    rect.right = x + length;
}

上面update(long fps)方法中的fps从我的View类中的run()方法传递:

public void run() {
    while (playing) {
        // Capture the current time in milliseconds
        startTime = System.currentTimeMillis();
        // Update & draw the frame
        if (!paused) {
            onUpdate();
        }
        draw();
        // Calculate the fps this frame
        thisTime = System.currentTimeMillis() - startTime;
        if (thisTime >= 1) {
            fps = 1000 / thisTime;
        }
    }
}

我的桨和球在View类中不断更新我的onUpdate()方法。

public void onUpdate() {
    // Update objects' positions
    paddle1.update(fps);
    ball.update(fps);
    AI(paddle2);
}

如何使用我已经为每个新桨定义的桨式速度将速度限制附加到我的AI桨上?我已经尝试修改AI(Paddle paddle)方法以合并+/- (paddleSpeed / fps),并且似乎根本不会影响桨。也许我只是实施了错误,但是任何帮助都很棒!

以使AI以稳定的速度移动桨,而不是跳到正确的位置,只需尝试使桨的中间与球中间保持一致:

public void AI(Paddle paddle) {
    RectF paddleRect = paddle.getRect();
    RectF ballRect = ball.getRect();
    float ballCenter = (ballRect.left + ballRect.right) / 2;
    float paddleCenter = (paddleRect.left + paddleRect.right) / 2;
    if (ballCenter < paddleCenter) {
        setMovementState(LEFT);
    }
    else {
        setMovementState(RIGHT);
    }
}

然后在onUpdate内拨打AI(paddle2)后,致电paddle2.update(fps)。这样,您就不会重复使用绘图代码。您会注意到,如果球比桨快得多,AI桨可能无法完美。在这种情况下,您可以使用数学来预测球最终会在哪里开始并到达那里。

最新更新