我正在制作一个迷宫游戏,我一直在努力编写碰撞检测代码。 Ball(Number 4)应该仅在sandimage(分配给数字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);
}
}
答案 0 :(得分:0)
你需要做的是让它获得球将要去的部分的坐标。因此,如果用户按下向下箭头,它将获得坐标,检查数组中的该项是否为白色,然后是否移动。
此外,你绝对应该为地图使用2D数组而不是1d数组,这样你就可以通过x,y访问位置。
int[][] map1 = {firstRow of stuff},{second row of stuff}, {etc};
然后boolean isTouchingWhite = map1[x][y] == 2;
答案 1 :(得分:0)
在我看来,你在移动石头之前没有检查过边界。以下是我将如何移动代码,从您显示的内容开始:
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