gpt4 book ai didi

java - 使用java中的循环绘制多个矩形,并进行碰撞检测,如果发生碰撞,则更改其x和y坐标(随机)。

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:11 24 4
gpt4 key购买 nike

查了很多资料,还是没能解决这个问题。我想生成 n 个数字矩形并将它们绘制在屏幕上。 X、Y 是随机生成的,宽度和高度基于字体大小。我的目标是在屏幕上随机放置 n 个单词,而不与现有矩形重叠。我使用矩形进行碰撞检测。

private List<Rectangle> rectList = new ArrayList<Rectangle>();

public boolean checkForCollision(Rectangle r) {
boolean collision = false;
if (rectList.size() == 0) {
rectList.add(r);
System.out.println("Adding First");
return collision;
} else {

// loop through the list
Rectangle currRectangle;
for (int i = 0; i < rectList.size(); i++) {
currRectangle = rectList.get(i);
if (r.intersects(currRectangle)) {
System.out.println(r.toString());
System.out.println(currRectangle.toString());
System.out.println("=========================");

return collision;

}
}
System.out.println("No collision");
rectList.add(r);
return !collision;
}
}

这就是我创建矩形并在其上绘制单词的方法。我在这里使用循环。

        int width = graphics.getFontMetrics().stringWidth(temp.getWord());
int height = graphics.getFontMetrics().getHeight();

Rectangle newRectangle = new Rectangle(rand.nextInt(1250)+1, rand.nextInt(650)+1, width, height);
int xCordinate = (int)newRectangle.getX();
int yCordinate = (int) newRectangle.getY();

while(collisonChecker.checkForCollision(newRectangle)){
//newRectangle = new Rectangle(rand.nextInt(1250)+1, rand.nextInt(650)+1, width, height);
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
collisonChecker.checkForCollision(newRectangle);

}
graphics.drawRect((int)newRectangle.getX(), (int)newRectangle.getY(), (int)newRectangle.getWidth(), (int)newRectangle.getHeight());
newRectangle.setLocation(rand.nextInt(1250)+1,rand.nextInt(650)+1);
graphics.drawString(temp.getWord().trim(), (int)newRectangle.getX(),(int)newRectangle.getY() );

最佳答案

你永远不会改变你的返回值。不管是否发生碰撞,该方法都会返回 false。将返回值设置为 trueidle for 循环中存在冲突,这应该可以解决问题

我希望至少有一点帮助

关于java - 使用java中的循环绘制多个矩形,并进行碰撞检测,如果发生碰撞,则更改其x和y坐标(随机)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34536433/

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