我已经创建了一个简单的演绎在安卓工作室的经典乒乓游戏的大学课程。在这一点上,几乎一切都准备好了,除了我创造了一个不可战胜的人工智能为敌人的桨。我用默认的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;
}上面的fps方法中的update(long fps)方法是从update(long fps)类中的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;
}
}
}在我的onUpdate()方法中,我的桨和球在View类中不断更新。
public void onUpdate() {
// Update objects' positions
paddle1.update(fps);
ball.update(fps);
AI(paddle2);
}如何使用我已经为每一个新的桨定义的桨速度来限制我的AI桨的速度?我已经尝试过修改AI(Paddle paddle)方法以合并+/- (paddleSpeed / fps),它似乎根本不影响桨。也许我只是把它搞错了,但是任何帮助都是很棒的!
发布于 2017-05-05 01:32:25
要使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);
}
}然后,在您调用AI(paddle2)在onUpdate内部,调用paddle2.update(fps)。这样,您就不会重复使用绘图代码了。你会注意到,如果球比桨快得多,AI桨可能做得不太好。在这种情况下,您可以使用数学来预测球会在哪里结束,并努力达到目标。
https://stackoverflow.com/questions/43794541
复制相似问题