我创建了一个非常简单的程序,我使用paint画了一个迷宫(方法fillRect
用于创建迷宫的墙),并且我创建了一个使用keyListener
移动的精灵。我想实现一个简单的(如我在通勤科学的第一年)碰撞检测,以防止精灵在迷宫的墙壁上移动。因为迷宫是用近400行代码绘制的,所以我不会包含它。创建简单的碰撞检测
import java.awt.*;
import java.applet.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class IndeProj extends Applet implements KeyListener {
//KEY LISTENER INFO FOR MY SPRITE
public int x = 10;
public int y = 575;
public boolean keyUp;
public boolean keyDown;
public boolean keyLeft;
public boolean keyRight;
public void paint(Graphics g) {
//drawMaze
drawMazeHorizontalLines(g);
drawMazeVerticalLines(g);
//SPRITE STUFF
addKeyListener(this);
this.MoveRect(g,x,y);
}
public void drawMazeHorizontalLines(Graphics g)
{
//This method draws the horizontal lines of the maze using the method `fillRect(x,y,w,h)`
}
public void drawMazeVerticalLines (Graphics g)
{
//This method draws the vertical lines of the maze using `fillRect(x,y,w,h)`
}
public void MoveRect(Graphics g, int x, int y) //Draws Sprite
{
g.setColor(Color.green);
g.fillRect(x,y,20,20);
g.setColor(Color.yellow); //Sprite body
g.fillRect(x,y,20,20);
g.setColor(Color.green); //Sprite eyes
g.fillRect(x,y,7,7);
g.fillRect((x+13),y,7,7);
g.setColor(Color.blue); //Sprite pants
g.fillRect(x,(y+13),20,7);
g.setColor(Color.black); //Sprite mouth
g.fillRect((x+6),(y+9),8,2);
}
public void keyPressed(KeyEvent e) //Moves Sprite
{
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y+=1;
y+=0;
} if (e.getKeyCode() == KeyEvent.VK_UP) {
y-=1;
y-=0;
} if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x-=1;
x-=0;
} if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x+=1;
x+=0;
}
repaint();
}
public void keyReleased(KeyEvent e) //Stops Sprite
{
keyUp = keyDown = keyLeft = keyRight = false;
}
}
我想这样,当它撞到一堵墙(使用x
和y
坐标)精灵停止做它,精灵将停止移动。