在检测玩家与许多相同对象(在本例中为墙砖)之间的碰撞时,我遇到了问题。问题是我的程序仅在我与最后添加的墙砖接触时才检测到碰撞。这是用java写的...
我正在使用矩形(它们的相交方法)来检测碰撞。
代码示例:
更新瓷砖:
for (int i = 0; i < wallTileArr.size(); i++)
{
wallTile = wallTileArr.get(i);
wallTile.update(p);
if(wallTile.getBounds().intersects(Screen.getBounds()))
{
wallTile.draw = true;
}
else if(!wallTile.getBounds().intersects(Screen.getBounds()))
{
wallTile.draw = false;
}
}
这是我用瓷砖制作墙的课程:
public Wall(int x, int y, int length, int dir, WallTile wallTile)
{
this.x = x;
this.y = y;
this.length = length;
this.wallTile = wallTile;
for(int i = 0; i < length; i++)
{
if (dir == 0)
{
Methods.addWallTile(new WallTile(x+(wallTile.size*i), y));
}
else if (dir == 1)
{
Methods.addWallTile(new WallTile(x, y+(wallTile.size*i)));
}
else if (dir != 0 || dir != 1)
{
System.out.println("Error in setting direction: 0 = horizontal, 1 = vertical. Your input is: "+dir );
//Methods.Exit(1);
}
}
}
这是我用墙壁制作房间或房屋的课程:
public HouseSmall_1(int x, int y,int size, int rotation, WallTile wallTile)
{
this.x = x;
this.y = y;
this.wallTile = wallTile;
this.size = size;
if (rotation == 0)
{
Methods.addWall(new Wall(x, y, size, 1, wallTile));
Methods.addWall(new Wall(x+(size*wallTile.size), y, size, 1, wallTile));
Methods.addWall(new Wall(x, y, size, 0, wallTile));
Methods.addWall(new Wall(x, y+(size*wallTile.size), (size)/2, 0, wallTile));
Methods.addWall(new Wall(x+wallTile.size+((size*wallTile.size)/2), y+(size*wallTile.size),(size/2), 0, wallTile));
}
}
将瓷砖和墙壁添加到它们的 arrayList 中的代码:
public static void addWallTile(WallTile wallTile)
{
Controller.wallTileArr.add(wallTile);
}
public static void addWall(Wall wall)
{
Controller.wallArr.add(wall);
}
更新 wallTile.java 文件中的碰撞代码:
public void update(Player p)
{
x+=Screen.movementX;
y+=Screen.movementY;
if(getBounds().intersects(p.upGetBounds()))
{
p.walk = false;
}
else
{
p.walk = true;
}
}
为什么会这样?你建议我如何解决它?
随时索取更多代码示例!