Results 1 to 13 of 13
  1. #1
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

    Default Help with mouse moving object and colisions

    Hello I'm having a problem in my programing, i drag a ball with mouse and i when it colides with other ball it stays there and don't overlap it and i don't know how to do it, can anyone help me?

    Java Code:
    package BinarySearchT;
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener
    {
    
      private static final int BALL_DIAMETER = 50; // Diameter of ball
      private static final int BALL_DIAMETER2 = 50;
      //--- instance variables
      /** Ball coords. Changed by mouse listeners. Used by paintComponent. */
      private int x1 = 50; // x coord - set from drag
      private int y1 = 50; // y coord - set from drag
      private int x2 = 200; // starting x coord for 2nd ball
      private int y2 = 200; //starting y coord for 2nd ball
      private int x3 = 75;
      private int y3 = 150;
    
      /** Position in ball of mouse press to make dragging look better. */
      private int _dragFromX = 0; // pressed this far inside ball's
      private int _dragFromY = 0; // bounding box.
      private int xInsideBall = 0; //coordinates of where the mouse is pressed inside second ball
      private int yInsideBall = 0; //is pressed inside second ball
      private int x3InsideBall = 0; //coordinates of where the mouse is pressed inside second ball
      private int y3InsideBall = 0; //is pressed inside second ball
    
      /** true means mouse was pressed in ball and still in panel.*/
      private boolean _canDrag = false;
      private boolean _canDrag2 = false;
      private boolean _canDrag3 = false;
    
      private String TEXT = "Teste";
      private String TEXT2 = "Teste2";
      private String TEXT3 = "Teste3";
    
    
    
    
      /** Constructor sets size, colors, and adds mouse listeners.*/
      public DragBallPanel()
      {
        setPreferredSize(new Dimension(400, 400));
        setBackground(Color.white);
        //setForeground(Color.BLUE);
        //--- Add the mouse listeners.
        this.addMouseListener(this);
        this.addMouseMotionListener(this);
    
        // add the keylistener!
        this.addKeyListener(this);
        // make sure the panel is focusable
        setFocusable(true);
      }//endconstructor
    
      /** Ball is drawn at the last recorded mouse listener coordinates. */
      public void paintComponent(Graphics g)
      {
        super.paintComponent(g); // Required for background.
        //g.drawRect(x1, y1, 10, 20);
        g.setColor(Color.DARK_GRAY);
        g.drawLine(x1+25, y1+45, x2+25, y2);
        
        g.drawLine(x1+25, y1+45, x3+25, y3);
        g.setColor(Color.DARK_GRAY);
    
        g.drawOval(x1, y1, BALL_DIAMETER, BALL_DIAMETER);
        g.drawString(TEXT, x1+10, y1+25);
        
        g.drawOval(x2, y2, BALL_DIAMETER2, BALL_DIAMETER2);
        g.drawString(TEXT2, x2+10, y2+25);
        
        g.drawOval(x3, y3, BALL_DIAMETER2, BALL_DIAMETER2);
        g.drawString(TEXT3, x3+10, y3+25);
    
      }//end paintComponent
    
      public void mousePressed(MouseEvent e)
      {
        int x = e.getX(); // Save the x coord of the click
        int y = e.getY(); // Save the y coord of the click
    
        //bola 1
        if (x >= x1 && x <= (x1 + BALL_DIAMETER) && y >= y1 && y <= (y1 + BALL_DIAMETER))
        {
          _canDrag = true;
          _dragFromX = x - x1; // how far from left
          _dragFromY = y - y1; // how far from top
        }
        else
        {
          _canDrag = false;
        }
    
        //bola 2
        if(x >= x2 && x <= (x2 + BALL_DIAMETER2) && y >= y2 && y <= (y2 + BALL_DIAMETER2) )
        {
          _canDrag2 = true;
          xInsideBall = x - x2;
          yInsideBall = y - y2;
        }
        else
        {
          _canDrag2 = false;
        }
        //bola 3
        if(x >= x3 && x <= (x3 + BALL_DIAMETER2) && y >= y3 && y <= (y3 + BALL_DIAMETER2) )
        {
          _canDrag3 = true;
          x3InsideBall = x - x3;
          y3InsideBall = y - y3;
        }
        else
        {
          _canDrag3 = false;
        }
      }//end mousePressed
    
      public void mouseDragged(MouseEvent e)
      {
          double p, p1;
    
          p = Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));
          p1 = Math.sqrt(Math.pow((x1 - x3), 2) + Math.pow((y1 - y3), 2));
            
        // True only if button was pressed inside ball.
        //--- Ball pos from mouse and original click displacement
        if (_canDrag)
        {
    
          x1 = e.getX() - _dragFromX;
          y1 = e.getY() - _dragFromY;
    
          x1 = Math.max(x1, 0);
          x1 = Math.min(x1, getWidth() - BALL_DIAMETER);
          y1 = Math.max(y1, 0);
          y1 = Math.min(y1, getHeight() - BALL_DIAMETER);
    
    
          //collision x1 - x2
          if(p < BALL_DIAMETER ){
              System.out.println("collision");
    
    
               //--- Don't move the ball off the screen sides
          x1 = Math.max( x2-BALL_DIAMETER, 400 - BALL_DIAMETER);
          //x1 = Math.min(x1, getWidth() - BALL_DIAMETER);
    
          //--- Don't move the ball off top or bottom
          y1 = Math.max(y2-BALL_DIAMETER, 400 -BALL_DIAMETER);
          y1 = Math.min(y1, getHeight() - BALL_DIAMETER);
    
             
    
              
         }
    
           //collision x1 - x3
           if(p1 < BALL_DIAMETER){
              System.out.println("collision");
    
              x1 = Math.max(x3,getHeight() );
              x1 = Math.min(x3,0);
              y1 = Math.max(y3,getHeight() );
              y1 = Math.min(y3,0 );
            
           }
    
           this.repaint(); // Repaint because position changed.
        }
            
        if (_canDrag2)
        {
          x2 = e.getX() - xInsideBall;
          y2 = e.getY() - yInsideBall;
          x2 = Math.max(x2, 0);
          x2 = Math.min(x2, getWidth() - BALL_DIAMETER2);
          y2 = Math.max(y2, 0);
          y2 = Math.min(y2, getHeight() - BALL_DIAMETER2);
    
          this.repaint(); // Repaint because position changed.
            }
    
        if (_canDrag3)
        {
          x3 = e.getX() - x3InsideBall;
          y3 = e.getY() - y3InsideBall;
          x3 = Math.max(x3, 0);
          x3 = Math.min(x3, getWidth() - BALL_DIAMETER2);
          y3 = Math.max(y3, 0);
          y3 = Math.min(y3, getHeight() - BALL_DIAMETER2);
    
          this.repaint(); // Repaint because position changed.
        }
    
      }//end mouseDragged
    
      public void keyPressed(KeyEvent ke)
      {
        System.out.println("key PRESSED");
        //int x = e.getX(); // Save the x coord of the click
        //int y = e.getY(); // Save the y coord of the click
        int dx = 10;
    
        switch (ke.getKeyCode())
        {
          case KeyEvent.VK_LEFT: // move x coordinate left
            x1 -= dx;
            x1 = Math.max(x1, 0);
            break;
          case KeyEvent.VK_RIGHT: // move x coordinate right
            x1 += dx;
            x1 = Math.min(x1, getWidth() - BALL_DIAMETER);
        }
        this.repaint();
      }
    
      public void mouseMoved (MouseEvent e) {} // ignore these events
      public void mouseEntered (MouseEvent e) {} // ignore these events
      public void mouseClicked (MouseEvent e) {} // ignore these events
      public void mouseReleased(MouseEvent e) {} // ignore these events
      public void mouseExited (MouseEvent e) {} // ignore these events
      public void keyReleased (KeyEvent ke) {} // ignore this junk
      public void keyTyped (KeyEvent ke) {} // ignore this junk
    
      /** Add a main(), to make this an SSCCE. */
      public static void main(String[] args) {
    
     //   DragBallPanel dbp = new DragBallPanel();
     //   JOptionPane.showMessageDialog(null,dbp);
    
            JFrame window = new JFrame();
            window.setTitle("Drag Demo");
    
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.setContentPane(new DragBallPanel());
            Dimension minSize = new Dimension(600,480);
            window.setMinimumSize(minSize);
            window.pack();
            window.show();
      }
    }//endclass DragBallPanel

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,344
    Blog Entries
    7
    Rep Power
    20

    Default

    Balls are just circles in two dimensions; a circle is defined by its centre C and its radius R. Two circles (C1, R1) and (C2, R2) touch if and only if |C1-C2| <= R1+R2 where |C1-C2| is the distance between the two centres. Making them bounce off in the right direction is an entirely different problem.

    kind regards,

    Jos

  3. #3
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

    Default

    Ok, but i can detect if they colide, what i dont know is how they dont overlap.

  4. #4
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,344
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by macwadu View Post
    Ok, but i can detect if they colide, what i dont know is how they dont overlap.
    If both balls/circles don't overlap then |C1-C2| > R1+R2.

    kind regards,

    Jos

  5. #5
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default Use painter's algorithm

    I compiled and ran your code.
    It seems to perform some sort of reaction
    while the mouse has control over the
    'center ball'.

    I don't want to study this action.
    I'd rather you explain it, if this is
    a problem you want help with.

    Here is a fix to render a clean
    overlap of the images using what
    is commonly known as the painter's
    algorithm:


    Java Code:
        g.setColor(Color.white);
        g.fillOval(x1, y1, BALL_DIAMETER, BALL_DIAMETER);
        g.setColor(Color.DARK_GRAY);
        g.drawOval(x1, y1, BALL_DIAMETER, BALL_DIAMETER);
        g.drawString(TEXT, x1+10, y1+25);
        
        g.setColor(Color.white);
        g.fillOval(x2, y2, BALL_DIAMETER2, BALL_DIAMETER2);
        g.setColor(Color.DARK_GRAY);
        g.drawOval(x2, y2, BALL_DIAMETER2, BALL_DIAMETER2);
        g.drawString(TEXT2, x2+10, y2+25);
        
        g.setColor(Color.white);
        g.fillOval(x3, y3, BALL_DIAMETER2, BALL_DIAMETER2);
        g.setColor(Color.DARK_GRAY);
        g.drawOval(x3, y3, BALL_DIAMETER2, BALL_DIAMETER2);
        g.drawString(TEXT3, x3+10, y3+25);
    This modification to your code may not be
    what you want, but it is harmless, and
    improves the rendering's aesthetics.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    how they dont overlap
    What does "overlap" mean? When I drag a circle, it overlaps other circles with no problem.

  7. #7
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

    Default

    Thats my problem i dont the balls to do that overlap. I want the balls to dont intersect.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    i dont the balls to do that overlap
    Ok we misunderstood your problem.
    JosAH has given the formula for detecting if the balls touch or overlap.
    Stop moving the ball if they touch.

  9. #9
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

    Default

    Can you help me with the Stop moving the ball, i dont know how to do it.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,305
    Rep Power
    25

    Default

    Look at the code where the ball is being moved. Test if the new position will touch any of the other balls. If it does, do NOT move the ball.
    You'll need a list of the other balls so you can check each ones position. That could be done by having a class for each ball and a method that takes a Ball as arg and returns true if the balls touch.

  11. #11
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

    Default

    Tanks for the help, i'm going to trie

  12. #12
    paul pasciak is offline Senior Member
    Join Date
    Jul 2008
    Posts
    125
    Rep Power
    0

    Default

    If the balls do not overlap,
    which do you want them to do?

    1. push the other aside
    2. slip around the other
    3. halt unless pulled away from the other

  13. #13
    macwadu is offline Member
    Join Date
    Jun 2010
    Posts
    29
    Rep Power
    0

Similar Threads

  1. Drawing moving object
    By dotabyss in forum Java 2D
    Replies: 1
    Last Post: 02-16-2010, 11:20 PM
  2. Replies: 2
    Last Post: 02-01-2010, 05:45 PM
  3. Mouse Listener for mouse floating over object?
    By Krooger in forum AWT / Swing
    Replies: 1
    Last Post: 11-18-2009, 04:34 AM
  4. Moving Box
    By anilanar in forum New To Java
    Replies: 2
    Last Post: 08-30-2009, 12:29 PM
  5. change object color on mouse click
    By gotenks05 in forum Java Applets
    Replies: 1
    Last Post: 04-05-2009, 07:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •