gpt4 book ai didi

java - 完成了我的 Frog 游戏,但碰撞系统的精度出现了问题

转载 作者:行者123 更新时间:2023-11-30 07:44:50 24 4
gpt4 key购买 nike

所以我正在创建一个 Frog 游戏,我已经得到了一切,但我遇到了一个小问题,我的碰撞系统非常不一致,我一直在试图找出是什么,但我不太明白它是什么。我希望它在碰到矩形时立即停止。任何帮助都会得到帮助。

import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
public class frogger
{
static double frogX = .5;
static double frogY = .02;
static double frogW = .02;
static double frogH = .02;
static double halfWidth = .05;
static double halfHeight = .02;

static double speeds[] = {.02, .03, .035 , .040, .043, .046, .060, .070};

static Rectangle2D.Double[] rectangles = {new Rectangle2D.Double(.45 , .12 , .1 , .04), new Rectangle2D.Double(.45 , .27 , .1 , .04), new Rectangle2D.Double(.45 , .42 , .1 , .04),
new Rectangle2D.Double(.45 , .57 , .1 , .04), new Rectangle2D.Double(.45 , .72 , .1 , .04), new Rectangle2D.Double(.45 , .87 , .1 , .04), new Rectangle2D.Double(.45 , .92 , .1 , .04)};

public static void drawscene()
{
StdDraw.clear();
StdDraw.setPenColor(StdDraw.GREEN);
StdDraw.filledRectangle(frogX, frogY, frogW, frogH);
StdDraw.setPenColor(StdDraw.RED);
for(int i = 0; i < rectangles.length; i++)
{
StdDraw.filledRectangle(rectangles[i].x + halfWidth, rectangles[i].y - halfHeight, halfWidth, halfHeight);
}
StdDraw.show(1000/24);
}



public static void updateDirection()
{

for(int i = 0; i < rectangles.length; i++){
rectangles[i].x += speeds[i];
}

for(int i = 0; i < rectangles.length; i++){
if(rectangles[i].x + halfWidth >= .98 || rectangles[i].x + halfWidth <= .02){
speeds[i] *= -1;
}
}



if (StdDraw.isKeyPressed(KeyEvent.VK_UP))
{
frogY += .01;
}
else if(StdDraw.isKeyPressed(KeyEvent.VK_DOWN))
{
frogY -= .01;
}
else if(StdDraw.isKeyPressed(KeyEvent.VK_LEFT))
{
frogX -= .01;
}
else if(StdDraw.isKeyPressed(KeyEvent.VK_RIGHT))
{
frogX += .01;
}

}

public static void main(String[] args)
{
outerloop:
while(true)
{
frogger.drawscene();
frogger.updateDirection();
if (frogX >= 1 )
{
break;
}
if (frogX <= 0)
{

break;
}
if(frogY >= 1)
{
break;
}

Rectangle2D.Double frog = new Rectangle2D.Double(frogX - frogW, frogY + frogH, frogW * 2, frogH * 2);

for(int i = 0; i < rectangles.length; i++){
if(frog.intersects(rectangles[i])){
break outerloop;
}
}

}

// put whatever you want to display at the end of the game here


}
}

最佳答案

所以,我几乎肯定这与 Java 中 double 和 float 的不准确有关:

Why not use double or float to represent currency?

我从未使用过您在这里使用的库。当您需要更高精度时,推荐的解决方案通常是使用 BigDecimal 类。但是,我不能说我确定您将如何使用这个库来做到这一点。

关于java - 完成了我的 Frog 游戏,但碰撞系统的精度出现了问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com