[英]Maze Game Collision Detection
我现在正在制作迷宫游戏,一直在努力编写碰撞检测代码。 球(编号4)应该仅在沙像(分配给编号1)上移动,但不应在白色图像(数组中的编号2)上移动。 这是我用于地图的数组:
int [] map1 = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4,
2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2,
2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2,
2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
这是分配给数组中数字的按钮的代码:
for( int nCount= 0; nCount < 208; nCount++ ) //for loop which goes from 0 to 208
{
JGridButton[nCount] = new JButton(""); //inserts a button for every count in the for loop
JPanelnorth.add(JGridButton[nCount]); //this line of code adds the buttons to the named panel
JGridButton[nCount].setBorderPainted(false);
if(map1[nCount]==1) // the image on the button will be set to sandimage, if the number in the array = 1
{
JGridButton[nCount].setIcon(sandimage);
}
if(map1[nCount]==2) // the image on the button will be set to whiteimage, if the number in the array = 2
{
JGridButton[nCount].setIcon(whiteimage);
}
if(map1[nCount]== 4) // the image on the button will be set to goldenball, if the number in the array = 4
{
JGridButton[nCount].setIcon(goldenball);
}
if(map1[nCount]== 3) // the image on the button will be set to sandstone, if the number in the array = 3
{
JGridButton[nCount].setIcon(sandstone);
}
}
您需要做的是获取球将要到达的部分的坐标。 因此,如果用户按下向下箭头,它将获取坐标,请检查数组中的该项是否为白色,如果不是,则将其移动。
另外,您绝对应该对地图使用2D数组而不是1d数组,以便可以通过x,y访问位置。 int[][] map1 = {firstRow of stuff},{second row of stuff}, {etc};
然后boolean isTouchingWhite = map1[x][y] == 2;
在我看来,您在移动石头之前尚未检查边界。 从显示的内容来看,这是我将如何移动代码的方法:
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
int next = nPosition - 16;
if(source == Jbuttonup && next >= 0 && map1[next] == 1)
{
JButtoncompass.setIcon(iconCompassnorth);
JTextField3.setText("N");
// update the map
map1[next] = 4;
map1[nPosition] = 1;
nPosition = next;
// let the paint method draw the updated map.
repaint();
}
}
对于左检查边界,我将实现为(next >= 0 && (nPosition % 16) != 0)
,右边界检查应为(next < map1.length && (next % 16) != 0)
并且下边界检查应为(next < map1.length)
。 关键是检查map1[next] == 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.