我目前正在java中进行碰撞检测,我有一个来自不同类的两个对象,即鸟类和蠕虫。蠕虫在随机方向上移动,而鸟只在我希望他移动的时候移动,因为我是那个通过使用关键箭头按钮控制他的人。现在,如果两个物体发生碰撞,我只想让虫子消失,鸟儿就会留在那里。有人可以帮我怎么做吗?提前感谢您分享您的想法。
此代码来自我的世界级。
public void render()
{
setupStrategy();
x0_pixel = 0;
y0_pixel = 0;
x1_pixel = getWidth();
y1_pixel = getHeight();
x1_world = x1_pixel / meter;
y1_world = y1_pixel / meter;
Graphics2D g2d = (Graphics2D) strategy.getDrawGraphics();
g2d.setBackground(Color.lightGray);
g2d.clearRect(0, 0, x1_pixel, y1_pixel);
g2d.setColor(Color.BLACK);
for (double x = 0; x < x1_world; x++)
{
for (double y = 0; y < y1_world; y++)
{
int xx = convertToPixelX(x);
int yy = convertToPixelY(y);
g2d.drawOval(xx, yy, 2, 2);
}
}
for (Worm worm : worms)
{
for (Sprite bird : birds)
{
if (!collides())
{
bird.render(g2d);
worm.render(g2d);
}
}
}
g2d.dispose();
strategy.show();
Toolkit.getDefaultToolkit().
sync();
}
public void start() throws InterruptedException
{
long prevLoopStart = System.nanoTime();
Avg avg = new Avg();
while (true)
{
final long loopStart = System.nanoTime();
final long dt = loopStart - prevLoopStart;
for (Worm worm : worms)
{
worm.move(dt);
}
for (Bird bird : birds)
{
bird.move(dt);
}
render();
Collides();
frame.onFpsUpdated(1.0 / dt * SECOND, avg.add(loopStart));
final long elapsed_ns = System.nanoTime() - loopStart;
long expected_elapsed_ms = 1000 / 60;
long elapsed_ms = (long) (elapsed_ns / (1000.0 * 1000.0));
long sleep_ms = expected_elapsed_ms - elapsed_ms;
if (sleep_ms > 0)
{
Thread.sleep(sleep_ms /* ms */);
}
prevLoopStart = loopStart;
}
}
private boolean Collides()
{
ArrayList<Sprite> toDisappear = new ArrayList<Sprite>();
for (int i = 0; i < worms.size(); i++)
{
Sprite r1 = worms.get(i);
for (int j = i + 1; j < birds.size(); j++)
{
Sprite r2 = birds.get(j);
if (r1 == r2)
{
continue;
}
Rectangle me = r1.getBounds();
Rectangle him = r2.getBounds();
if (me.intersects(him))
{
collision = true;
toDisappear.add(r1);
toDisappear.add(r2);
}
toDisappear.remove(r1);
todisappear.remove(r2);
}
}
return collision;
}
答案 0 :(得分:1)
本书提供了很多关于“碰撞检测”(阅读第2章和第3章)的信息以及与Java游戏编程相关的其他主题。
答案 1 :(得分:0)
答案 2 :(得分:0)
你有一个嵌套的for循环来检查鸟类和蠕虫之间的碰撞。如果发生碰撞,它们都不会被画出来。您的代码也错误地多次绘制鸟类和蠕虫。
for (Worm worm : worms){
for (Sprite bird : birds){
if (!collides()){
bird.render(g2d);
worm.render(g2d);
}
}
}
正确的方法是在发生碰撞时从列表中删除蠕虫:
for (Iterator<Worm> wit = worms.getIterator(); wit.hasNext(); ){
Worm worm = wit.next();
for (Sprite bird : birds){
if (worm.collidesWith(bird)){
wit.remove();
break;
}
}
}
for (Worm worm : worms){
worm.render(g2d);
}
for (Sprite bird : birds){
bird.render(g2d);
}
现在我假设您将在类蠕虫中实现一个boolean collidesWith(Bird other)方法,以便您可以将该特定蠕虫与您作为参数获得的鸟进行比较。或者做一个这样的功能:
boolean collidesWormBird(Sprite worm, Sprite bird){
Rectangle me = worm.getBounds();
Rectangle him = bird.getBounds();
return me.intersects(him);
}