如何禁止我的Sprite对象在canvas的某些坐标上移动

时间:2016-09-26 06:53:07

标签: java

我想禁止我的Sprite对象移动画布的某些坐标。我怎样才能做到这一点 ?我到目前为止做了什么:

  1. 包project1;
  2. import java.awt.*;       
    // Using AWT's Graphics and Color 
    import java.awt.event.*; 
    // Using AWT's event classes and listener
    interfaces import javax.swing.*;    
    // Using Swing's components and containers 
    /**  
    * Custom Graphics Example: Using key/button to move a object left or right.
    * The moving object (sprite) is defined in its own class, with its own  
    * operations and can paint itself.  *  
    */  class Sprite {
    // Variables (package access)
    public int x;
    public int y;
    int width, height;
    // Use an rectangle for illustration
    Color color = Color.RED; // Color of the object
    // Constructor
    public Sprite(int x, int y, int width, int height, Color color) {
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
          this.color = color;
    }
    // Paint itself given the Graphics context
    public void paint(Graphics g) {
          g.setColor(color);
          g.fillRect(x, y, width, height); // Fill a rectangle
          // g.drawLine(20, 0, 20, 240);
          System.out.println("paint   X: "+x+"  Y: "+y);
    
          //System.out.println("paint 2nd   X: "+x+"  Y: "+y);    } } 
    
    
    public class Project1 extends JFrame {
    // Define constants for the various dimensions
        public static final int CANVAS_WIDTH = 400;
        public static final int CANVAS_HEIGHT = 240;
        public static final Color CANVAS_BG_COLOR = Color.CYAN;
        private DrawCanvas canvas;
        // the custom drawing canvas (an inner class extends JPanel)
        private  Sprite sprite;     // the moving object
        // Constructor to set up the GUI components and event handlers
        public Project1() {
          // Construct a sprite given x, y, width, height, color
          int x = 0,y = 0;
          sprite = new Sprite(CANVAS_WIDTH / 2 - 30, CANVAS_HEIGHT / 2 - 30,
                10, 10, Color.RED);
    
          // Set up a panel for the buttons
          JPanel btnPanel = new JPanel(new FlowLayout());
          JButton btnLeft = new JButton("Move Left ");
          btnPanel.add(btnLeft);
          btnLeft.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
    
                moveLeft();
    
    
                requestFocus(); // change the focus to JFrame to receive KeyEvent
             }
          });
    
           //JPanel btnPanel1 = new JPanel(new FlowLayout());
          JButton btnDown = new JButton("Move down ");
          btnPanel.add(btnDown);
          btnDown.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
                moveDown();
                requestFocus(); // change the focus to JFrame to receive KeyEvent
             }
          });
    
          JButton btnRight = new JButton("Move Right");
          btnPanel.add(btnRight);
          btnRight.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
                moveRight();
                requestFocus(); // change the focus to JFrame to receive KeyEvent
             }
          });
    
            JButton btnUp = new JButton("Move Up");
          btnPanel.add(btnUp);
          btnUp.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
                moveUp();
                requestFocus(); // change the focus to JFrame to receive KeyEvent
             }
          });
    
          // Set up the custom drawing canvas (JPanel)
          canvas = new DrawCanvas();
          canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
    
          // Add both panels to this JFrame
          Container cp = getContentPane();
          cp.setLayout(new BorderLayout());
          cp.add(canvas, BorderLayout.CENTER);
          cp.add(btnPanel, BorderLayout.SOUTH);
    
          // "super" JFrame fires KeyEvent
          addKeyListener(new KeyAdapter() {
             @Override
             public void keyPressed(KeyEvent evt) {
                switch(evt.getKeyCode()) {
                   case KeyEvent.VK_LEFT:  moveLeft();  break;
                   case KeyEvent.VK_RIGHT: moveRight(); break;
                   case KeyEvent.VK_DOWN: moveDown(); break;
                   case KeyEvent.VK_UP: moveUp(); break;
                }
             }
          });
    
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setTitle("Move a Sprite");
          pack();            // pack all the components in the JFrame
          setVisible(true);  // show it
          requestFocus();    // "super" JFrame requests focus to receive KeyEvent    }
         // Helper method to move the sprite left    private void moveLeft() {
          // Save the current dimensions for repaint to erase the sprite
          int savedX = sprite.x;
          // update sprite
          sprite.x -= 10;
          // Repaint only the affected areas, not the entire JFrame, for efficiency
          canvas.repaint(savedX, sprite.y, sprite.width, sprite.height); // Clear old area to background
          canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location    }
    
        // Helper method to move the sprite right    private void moveRight() {
          // Save the current dimensions for repaint to erase the sprite
          int savedX = sprite.x;
          // update sprite
          sprite.x += 10;
          // Repaint only the affected areas, not the entire JFrame, for efficiency
          canvas.repaint(savedX, sprite.y, sprite.width, sprite.height); // Clear old area to background
          canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint at new location    }
         private void moveDown() {
          //Save the current dimensions for repaint to erase the sprite
          int saved = sprite.y;
          // update sprite
          sprite.y += 10;
          // Repaint only the affected areas, not the entire JFrame, for efficiency
         canvas.repaint( sprite.x, saved, sprite.width, sprite.height); // Clear old area to background
          canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location    }   private void moveUp() {
          //Save the current dimensions for repaint to erase the sprite
          int savedY = sprite.y;
          // update sprite
          sprite.y -= 10;
          // Repaint only the affected areas, not the entire JFrame, for efficiency
         canvas.repaint( sprite.y, savedY, sprite.width, sprite.height); // Clear old area to background
          canvas.repaint(sprite.x, sprite.y, sprite.width, sprite.height); // Paint new location    }
    
         // Define inner class DrawCanvas, which is a JPanel used for custom drawing    class DrawCanvas extends JPanel {
          @Override
          public void paintComponent(Graphics g) {
             super.paintComponent(g);
             setBackground(CANVAS_BG_COLOR);
             sprite.paint(g);  // the sprite paints itself
          }    }
         // The entry main() method    public static void main(String[] args) {
          // Run GUI construction on the Event-Dispatching Thread for thread safety
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new Project1(); // Let the constructor do the job
             }
          });
        }
    
    
    }
    

1 个答案:

答案 0 :(得分:-1)

代码中的注释太多,难以发现问题,但是,从您的问题出发,您可以使用网格来跟踪x& y坐标。然后检查对象所在的坐标是否与您不希望对象移动到的位置相对应。我在模拟中使用相同的策略。