Hi guys, so I've been making this java program to simulate a rather simple pacman, I've been doing fine until I reached the point where I can't figure out how to put a restriction on the pacman so he doesn't walk thru a wall. Here is my source code:
Background.pngpacman.jpg
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; public class Pacman extends JPanel implements ActionListener, KeyListener { Timer t = new Timer(5, this); int x = 75, y = 80, velX = 0, velY = 0; private BufferedImage sheet; private BufferedImage sheet1; private int frame; public Pacman() { t.start(); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); } @Override public void paintComponent(Graphics g) { try { sheet = ImageIO.read(Pacman.class.getResource("/images/Background.png")); } catch (IOException ex) { Logger.getLogger(Pacman.class.getName()).log(Level.SEVERE, null, ex); } try { sheet1 = ImageIO.read(Pacman.class.getResource("/images/pacman.png")); } catch (IOException ex) { Logger.getLogger(Pacman.class.getName()).log(Level.SEVERE, null, ex); } if (sheet != null) { g.drawImage(sheet, 0, 0, null); } g.drawImage(sheet1.getSubimage(629 + (frame / 3) * (15 + 2), 51, 15, 15), x, y, null); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.GREEN); g2.fillRect(66, 98, 32, 24); } @Override public void actionPerformed(ActionEvent e) { repaint(); if (x < 7 || x > 143) { velX = 0; } if (y < 8 || y > 199) { velY = 0; } x += velX; y += velY; } public void up() { if (y > 199) { y = 199; } velY = -5; velX = 0; } public void down() { if (y < 8) { y = 8; } velY = 5; velX = 0; } public void left() { if (x > 143) { x = 143; } velX = -5; velY = 0; } public void right() { if (x < 7) { x = 7; } velX = 5; velY = 0; } public void walls() { } @Override public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_UP) { up(); } if (code == KeyEvent.VK_DOWN) { down(); } if (code == KeyEvent.VK_RIGHT) { right(); } if (code == KeyEvent.VK_LEFT) { left(); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } }
I would like to get some help to figure out how to avoid the pacman from entering a wall. I have drawn a rectangle but how do I declare that the pacman's speed should change to O "velX=0 or velY=0" when it touches the wall?
Say for the following rectangle
what could I do in the methodg2.setColor(Color.GREEN); g2.fillRect(66, 98, 32, 24);public void walls () {}