2017-01-05 3 views
-1

Я хочу сделать прямоугольник, который следует за другим прямоугольником, где бы ни перемещался игрок. Однако я не могу найти способ сделать это. Что я могу сделать, чтобы заставить его следовать за другим прямоугольником?Как сделать прямоугольник, следуя за другим прямоугольником в Java

Вот мой код (неиспользуемые переменные для последующего использования):

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 

import javax.swing.*; 
import javax.swing.Timer; 

public class Game{ 

public static void main(String[] args) { 

    final JFrame frame = new JFrame("Game"); 
    frame.setSize(500, 500); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setResizable(false); 
    frame.setLocationRelativeTo(null); 
    frame.add(new GamePanel()); 
    frame.setVisible(true); 

} 

@SuppressWarnings("serial") 
private static class GamePanel extends JPanel implements ActionListener, KeyListener{ 

    private int x = 0; 
    private int y = 0; 
    private int ax = 0; 
    private int ay = 0; 
    private boolean clicked0 = true; 
    private boolean clicked01 = true; 
    private boolean clicked = false; 
    private boolean clicked1 = false; 
    private boolean clicked2 = false; 
    private boolean clicked3 = false; 
    private boolean clicked4 = false; 
    private boolean clicked5 = false; 
    private static boolean enteredZone = false; 
    private static boolean enteredZone1 = false; 
    private static boolean enteredZone2 = false; 
    private static boolean enteredZone3 = false; 
    private static boolean enteredZone4 = false; 
    private static boolean updcl1 = false; 
    private static boolean updcl = false; 
    private static boolean updcl2 = false; 
    private static boolean updcl3 = false; 
    private static boolean updcl4 = false; 
    private static boolean updcl5 = false; 
    private int enmovex; 
    private int enmovey; 
    private int enmx = 1; 
    private int enmy = 0; 
    private int movea = 1; 
    private int moveb = 400; 
    private int moveby = 250; 
    private int moveitfx = 5; 
    private int moveitbx = 5; 
    private int moveitfy = 5; 
    private int moveitby = 5; 
    private static boolean screen1 = false; 
    private static boolean screen2 = false; 
    private static boolean screen3 = false; 
    Random rand = new Random(); 
    int intrand = rand.nextInt(5) + 1; 
    Timer anitm = new Timer(5, this); 

    public GamePanel() { 

     super(); 
     setSize(500, 500); 
     setBackground(Color.BLACK); 
     addMouseListener(new MouseListenerImpl()); 
     addMouseMotionListener(new MouseMotionListenerImpl()); 
     addKeyListener(this); 
     setFocusable(true); 
     setFocusTraversalKeysEnabled(false); 

    } 

    @Override 
    public void paintComponent(Graphics g) { 

     super.paintComponent(g); 

     if(screen1 == false){ 
     g.setColor(Color.GREEN); 
     g.drawRect(150, 75, 200, 100); 
     g.drawRect(150, 275, 200, 100); 
     g.setColor(Color.ORANGE); 
     g.setFont(new Font("TimesRoman", Font.PLAIN, 40)); 
     g.drawString("Play", 218, 130); 
     g.setColor(Color.RED); 
     g.drawString("Quit", 218, 330); 
     // anitm.stop(); 
     } 

     if (x > 150 && y > 75 && x < 350 && y < 175 && screen1 == false|| enteredZone) { 
      g.setColor(Color.ORANGE); 
      g.drawRect(150, 75, 200, 100); 
      updcl = true; 
      updateUI(); 
      if (clicked || enteredZone) { 
       g.setColor(Color.BLACK); 
       g.fillRect(-1, -1, 500, 500); 
       g.setColor(Color.RED); 
       g.setColor(Color.BLUE); 
       g.drawRect(20, 20, 70, 50); 
       g.setColor(Color.RED); 
       g.setFont(new Font("TimesNewRoman", Font.PLAIN, 14)); 
       g.drawString("<< Back", 30, 50); 
       g.setColor(Color.GREEN); 
       g.setFont(new Font("TimesRoman", Font.PLAIN, 25)); 
       g.drawString("Next >>", 384, 438); 
       g.setColor(Color.BLUE); 
       g.drawRect(370, 400, 110, 60); 
       enteredZone = true; 
       enteredZone1 = false; 
       updcl1 = false; 
       screen1 = true; 
       updateUI(); 
       if(x > 20 && y > 20 && x < 90 && y < 70 && screen1 == true && screen2 == false|| enteredZone1){ 
         g.setColor(Color.RED); 
         g.drawRect(20, 20, 70, 50); 
         updcl1 = true; 
         if(clicked1 || enteredZone1){ 
          enteredZone2 = false; 
          enteredZone3 = false; 
          enteredZone4 = false; 
          updcl3 = false; 
          screen1 = false; 
          screen2 = false; 
          screen3 = false; 

          enteredZone = false; 
          enteredZone1 = true; 
          updcl = false; 
          clicked = !clicked; 
          screen1 = false; 
          updateUI(); 
         } 
        } 
        if(x > 370 && y > 400 && x < 480 && y < 460 && screen1 == true || enteredZone2){ 
         g.setColor(Color.GREEN); 
         g.drawRect(370, 400, 110, 60); 
         updcl3 = true; 
         if(clicked3 || enteredZone2){ 
          enteredZone1 = false; 
          enteredZone2 = true; 
          updcl4 = false; 
          screen2 = true; 
          screen1 = false; 
          enteredZone3 = false; 
          enteredZone4 = false; 
          anitm.start(); 
          g.setColor(new Color(34, 157, 76)); 
          g.fillRect(0, 0, 500, 100); 
          g.setColor(new Color(4, 206, 15)); 
          g.fillRect(0, 100, 500, 100); 
          g.setColor(new Color(34, 157, 76)); 
          g.fillRect(0, 200, 500, 100); 
          g.setColor(new Color(4, 206, 15)); 
          g.fillRect(0, 300, 500, 100); 
          g.setColor(new Color(34, 157, 76)); 
          g.fillRect(0, 400, 500, 100); 
          g.setColor(Color.GREEN); 
          g.fillRect(moveb, moveby, 40, 40); 
          g.setColor(Color.BLUE); 
          g.drawRect(moveb, moveby, 40, 40); 
          if(moveb >= 455){ 
           moveitfx = 0; 
          } 
          if(moveb < 455){ 
           moveitfx = 5; 
          } 
          if(moveb <= 0){ 
           moveitbx = 0; 
          } 
          if(moveb > 0){ 
           moveitbx = 5; 
          } 
          if(moveby >= 435){ 
           moveitby = 0; 
          } 
          if(moveby < 435){ 
           moveitby = 5; 
          } 
          if(moveby <= 0){ 
           moveitfy = 0; 
          } 
          if(moveby > 0){ 
           moveitfy = 5; 
          } 
          if(intrand == 1){ 
           enmovey = 50; 
           g.setColor(Color.RED); 
           g.fillRect(enmovex, enmovey, 20, 20); 
          } 
          if(intrand == 2){ 
           enmovey = 150; 
           g.setColor(Color.RED); 
           g.fillRect(enmovex, enmovey, 20, 20); 
          } 
          if(intrand == 3){ 
           g.setColor(Color.RED); 
           enmovey = 250; 
           g.fillRect(enmovex, enmovey, 20, 20); 
          } 
          if(intrand == 4){ 
           enmovey = 350; 
           g.setColor(Color.RED); 
           g.fillRect(enmovex, enmovey, 20, 20); 
          } 
          if(intrand == 5){ 
           enmovey = 450; 
           g.setColor(Color.RED); 
           g.fillRect(enmovex, enmovey , 20, 20); 
          } 
          repaint(); updateUI(); 
         } 
        } 
        if(x < 370 || y < 400 || x > 480 || y > 460){ 
         updcl3 = false; 
        } 
       } 
     } 
     if(x > 150 && y > 275 && x < 350 && y < 375 && screen1 == false && screen2 == false && screen3 == false){ 
      g.drawRect(150, 275, 200, 100); 
      updcl2 = true; 
      if(clicked2){ 
       System.exit(0); 
      } 
     } 
     if(x < 150 || y < 275 || x > 350 || y > 375){ 
      updcl2 = false; 
     } 
      if(x < 150 || y < 75 || x > 350 || y > 175){ 
      updcl = false; 
     } 
      if(x < 370 || y < 400 || x > 480 || y > 460){ 
       updcl5 = false; 
      } 
} 

    private class MouseListenerImpl implements MouseListener { 

     @Override 
     public void mouseClicked(MouseEvent e) { 

     } 
    @Override 
    public void mouseEntered(MouseEvent arg0) { 

    } 
    @Override 
    public void mouseExited(MouseEvent arg0) { 

    } 
    @Override 
    public void mousePressed(MouseEvent arg0) { 

    } 
    @Override 
    public void mouseReleased(MouseEvent arg0) { 
     if(clicked0 && updcl == true){ 
      clicked = !clicked; 
      repaint(); updateUI(); 
      } 
      if(clicked && updcl1 == true){ 
       clicked1 = !clicked1; 
       repaint(); updateUI(); 
      } 
      if(updcl2 == true && clicked01){ 
       clicked2 = !clicked2; 
       repaint(); updateUI(); 
      } 
      if(updcl3 == true && clicked){ 
       clicked3 = !clicked3; 
       repaint(); updateUI(); 
      } 
      if(updcl4 == true && clicked3){ 
       clicked4 = !clicked4; 
       repaint(); updateUI(); 
      } 
      if(updcl5 == true && clicked3){ 
       clicked5 = !clicked5; 
       System.out.println("..."); 
       repaint(); updateUI(); 
      } 
      repaint(); updateUI(); 
    } 
    } 

    private class MouseMotionListenerImpl extends MouseMotionAdapter { 
     @Override 
     public void mouseMoved(MouseEvent e) { 
      x = e.getX(); 
      y = e.getY(); 
      //System.out.println("X: " + x +" Y: " + y); 
      repaint(); 
     } 
    } 

    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     ax = ax + movea; 
     ay = ay + movea; 
     if(ax >= 480 || ay >= 460){ 
      movea = -1; 
      repaint(); 
     } if(ax == 0 && ay == 0){ 
      movea = 1; 
     } 
     enmovex = enmovex + enmx; 
     enmovey = enmovey + enmx; 
     updateUI(); 
     repaint(); 
    } 

     public void keyPressed(KeyEvent e) {  
      int kc = e.getKeyCode(); 
     if(screen2 == true){ 
      if (kc == KeyEvent.VK_RIGHT) { 
       moveb = moveb + moveitfx; 
     } 
     if(kc == KeyEvent.VK_LEFT){ 
      moveb = moveb - moveitbx;; 
     } 
     if(kc == KeyEvent.VK_UP){ 
      moveby = moveby - moveitfy; 
     } 
     if(kc == KeyEvent.VK_DOWN){ 
      moveby = moveby + moveitby; 
     } 
     } 
     } 

     public void keyReleased(KeyEvent e) { 

     } 
     public void keyTyped(KeyEvent e) { 

     }  
    } 
} 
+0

вы заполнить пространство с кодом и вдруг вы понимаете, что вы не можете сделать это случилось !! – gpasch

+0

Что вы подразумеваете под "follow"? Какое точное поведение вы хотите? – MathSquared

+0

Я хочу, чтобы он медленно входил в прямоугольник. Как только он окажется внутри прямоугольника, он перестанет двигаться. И если мы уйдем, я хочу, чтобы он медленно двигался к прямоугольнику. –

ответ

0

Вы можете создать отдельный поток, который, чем бы отслеживать ваши формы, форма А перемещаемый игрока и форма Ь должна быть перенесена программой.

Вот рабочий пример, он не является гладким или сильно уточненным, так как основной код был скопирован здесь (http://www.java2s.com/Code/Java/Event/MoveShapewithmouse.htm) и расширен дальше, что можно прочитать здесь (https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html). Я не смотрел на ваш код, чтобы выяснить, где реализовать материал, так что это зависит от вас.

Я также добавил этот

public class Chase implements Runnable { 
    MyCanvas canvas; 

    public Chase(MyCanvas canvas) { 
     this.canvas = canvas; 
    } 

    @Override 
    public void run() { 
     try { 
      while(true) { 
       if(canvas.rect.getX() != canvas.rect2.getX()) { 
        int moveby = 2; 

        if(Math.abs(canvas.rect.getX() - canvas.rect2.getX()) < moveby) { 
         moveby = 1; 
        } 

        if(canvas.rect.getX() > canvas.rect2.getX()) { 
         canvas.rect2.setLocation(moveby + (int) canvas.rect2.getX(), (int) canvas.rect2.getY()); 
        } else { 
         canvas.rect2.setLocation(-moveby + (int) canvas.rect2.getX(), (int) canvas.rect2.getY()); 
        } 
       } 

       if(canvas.rect.getY() != canvas.rect2.getY()) { 
        int moveby = 2; 

        if(Math.abs(canvas.rect.getY() - canvas.rect2.getY()) < moveby) { 
         moveby = 1; 
        } 

        if(canvas.rect.getY() > canvas.rect2.getY()) { 
         canvas.rect2.setLocation((int) canvas.rect2.getX(), moveby + (int) canvas.rect2.getY()); 
        } else { 
         canvas.rect2.setLocation((int) canvas.rect2.getX(), -moveby + (int) canvas.rect2.getY()); 
        } 
       } 

       canvas.repaint(); 
       Thread.sleep(50); 
      } 
     } catch(Exception exception) { 
      System.out.println(exception); 
     } 
    } 
} 

классу shapeMover.

Рабочий пример:

import java.applet.Applet; 
import java.awt.BasicStroke; 
import java.awt.BorderLayout; 
import java.awt.Canvas; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Frame; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Label; 
import java.awt.Rectangle; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 
import java.awt.event.MouseMotionListener; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 

import javax.swing.JApplet; 
//Use double buffering to remove rectangle flickers and make it repaint faster. 
public class shapeMover extends JApplet { 
    static protected Label label = new Label(
      "Drag rectangle around within the area"); 

    public void init() { 
     MyCanvas canvas = new MyCanvas(); 
     getContentPane().setLayout(new BorderLayout()); 
     getContentPane().add(canvas); 

     getContentPane().add("South", label); 
     (new Thread(new Chase(canvas))).start(); 
    } 

    public static void main(String s[]) { 
     Frame f = new Frame("ShapeMover"); 
     f.addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent e) { 
       System.exit(0); 
      } 
     }); 
     Applet applet = new shapeMover(); 
     f.add("Center", applet); 
     applet.init(); 
     f.pack(); 
     f.setSize(new Dimension(550, 250)); 
     f.setVisible(true); 
    } 

    public class Chase implements Runnable { 
     MyCanvas canvas; 

     public Chase(MyCanvas canvas) { 
      this.canvas = canvas; 
     } 

     @Override 
     public void run() { 
      try { 
       while(true) { 
        if(canvas.rect.getX() != canvas.rect2.getX()) { 
         int moveby = 2; 

         if(Math.abs(canvas.rect.getX() - canvas.rect2.getX()) < moveby) { 
          moveby = 1; 
         } 

         if(canvas.rect.getX() > canvas.rect2.getX()) { 
          canvas.rect2.setLocation(moveby + (int) canvas.rect2.getX(), (int) canvas.rect2.getY()); 
         } else { 
          canvas.rect2.setLocation(-moveby + (int) canvas.rect2.getX(), (int) canvas.rect2.getY()); 
         } 
        } 

        if(canvas.rect.getY() != canvas.rect2.getY()) { 
         int moveby = 2; 

         if(Math.abs(canvas.rect.getY() - canvas.rect2.getY()) < moveby) { 
          moveby = 1; 
         } 

         if(canvas.rect.getY() > canvas.rect2.getY()) { 
          canvas.rect2.setLocation((int) canvas.rect2.getX(), moveby + (int) canvas.rect2.getY()); 
         } else { 
          canvas.rect2.setLocation((int) canvas.rect2.getX(), -moveby + (int) canvas.rect2.getY()); 
         } 
        } 

        canvas.repaint(); 
        Thread.sleep(50); 
       } 
      } catch(Exception exception) { 
       System.out.println(exception); 
      } 
     } 
    } 
} 

class MyCanvas extends Canvas implements MouseListener, MouseMotionListener { 
    Rectangle rect = new Rectangle(0, 0, 100, 50); 
    Rectangle rect2 = new Rectangle(0, 0, 100, 50); 

    Graphics2D g2; 

    int preX, preY; 

    boolean isFirstTime = true; 

    Rectangle area; 

    boolean pressOut = false; 

    public MyCanvas() { 
     setBackground(Color.white); 
     addMouseMotionListener(this); 
     addMouseListener(this); 
    } 

    public void mousePressed(MouseEvent e) { 
     preX = rect.x - e.getX(); 
     preY = rect.y - e.getY(); 

     if (rect.contains(e.getX(), e.getY())) 
      updateLocation(e); 
     else { 
      shapeMover.label.setText("Drag it."); 
      pressOut = true; 
     } 
    } 

    public void mouseDragged(MouseEvent e) { 
     if (!pressOut) 
      updateLocation(e); 
     else 
      shapeMover.label.setText("Drag it."); 
    } 

    public void mouseReleased(MouseEvent e) { 
     if (rect.contains(e.getX(), e.getY())) 
      updateLocation(e); 
     else { 
      shapeMover.label.setText("Drag it."); 
      pressOut = false; 
     } 
    } 

    public void mouseMoved(MouseEvent e) { 
    } 

    public void mouseClicked(MouseEvent e) { 
    } 

    public void mouseExited(MouseEvent e) { 
    } 

    public void mouseEntered(MouseEvent e) { 
    } 

    public void updateLocation(MouseEvent e) { 
     rect.setLocation(preX + e.getX(), preY + e.getY()); 

     if (checkRect()) { 
      shapeMover.label.setText(rect.getX() + ", " + rect.getY()); 
     } else { 
      shapeMover.label.setText("drag inside the area."); 
     } 

     repaint(); 
    } 

    public void paint(Graphics g) { 
     update(g); 
    } 

    public void update(Graphics g) { 
     Graphics2D g2 = (Graphics2D) g; 
     Dimension dim = getSize(); 
     int w = (int) dim.getWidth(); 
     int h = (int) dim.getHeight(); 
     g2.setStroke(new BasicStroke(8.0f)); 

     if (isFirstTime) { 
      area = new Rectangle(dim); 
      rect.setLocation(w/2 - 50, h/2 - 25); 
      rect2.setLocation(w/2 + 150, h/2 - 25); 
      isFirstTime = false; 
     } 

     // Clears the rectangle that was previously drawn. 
     g2.setPaint(Color.white); 
     g2.fillRect(0, 0, w, h); 

     g2.setColor(Color.red); 
     g2.draw(rect); 
     g2.setColor(Color.black); 
     g2.fill(rect); 

     g2.setColor(Color.green); 
     g2.draw(rect2); 

    } 

    boolean checkRect() { 
     if (area == null) { 
      return false; 
     } 

     if (area.contains(rect.x, rect.y, 100, 50)) { 
      return true; 
     } 
     int new_x = rect.x; 
     int new_y = rect.y; 

     if ((rect.x + 100) > area.getWidth()) { 
      new_x = (int) area.getWidth() - 99; 
     } 
     if (rect.x < 0) { 
      new_x = -1; 
     } 
     if ((rect.y + 50) > area.getHeight()) { 
      new_y = (int) area.getHeight() - 49; 
     } 
     if (rect.y < 0) { 
      new_y = -1; 
     } 
     rect.setLocation(new_x, new_y); 
     return false; 
    } 
}