1

I am trying to get basic intersections to work with a game I am developing and because of that I need to define their hitboxes. However when using g2d.draw(rectangle) the rectangle doesn't move relative to its updated coordinates.

int x = 100 ;
int y = 100 ;
int x2 = x + 100;
int y2 = y + 100;

Rectangle hitbox = new Rectangle(x,y,x2,y2) ;

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //Graphical loop start
    g2d.draw(hitbox) ;
    repaint() ;
    //Graphical loop end
    }

The gameloop with the keylistener components

public void run() {

    while(running) {

        //Player movement
        if (left) {
            if (x <= -225) {
                x = 1440 ;
            }
            x = x - 2 ;
        }
        if (up) {
            if(y <= -225) {
                y = 900 ;
            }
            y = y - 2 ;
        }
        if (right) {
            if (x >= 1416) {
                x = -24 ;
            }
            x = x + 2;
        }
        if (down) {
            if (y >= 900) {
                y = -10 ;
            }
            y = y + 2 ;
        }
        //Player movement

        //ball movement
        if (cubey > y) {
            cubey-- ;
        }
        if(cubey < y) {
            cubey++ ;
        }
        if (cubex > x) {
            cubex-- ;
        }
        if (cubex < x) {
            cubex++ ;
        }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sumtinlazy
  • 337
  • 5
  • 17
  • perhaps you need to repaint each time the coordinates change (I am not sure about that though) – vefthym Jun 02 '15 at 14:38
  • Try `Rectangle#contains()`. – trashgod Jun 02 '15 at 14:39
  • See also [Collision detection with complex shapes](http://stackoverflow.com/a/14575043/418556). – Andrew Thompson Jun 02 '15 at 14:41
  • For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Jun 02 '15 at 14:42
  • `protected void paintComponent(Graphics g) { super.paintComponent(g); .. repaint() ;` Calling `repaint()` from within the paint methods is the wrong way to approach animation! One easy way to animate the painting of a component is to use a Swing `Timer` to call `repaint()`. – Andrew Thompson Jun 02 '15 at 14:44

1 Answers1

1

Based on provided code there is no connection between hitbox rectangle and coordinates what you change. Update rectangle with new x,y and then repaint.

Something like this:

public void run() {
    while(running) {
       //...
       hitbox.setBounds(x,y,100,100);
    }
}

even it's not efficient how your program flow should work.

Alex
  • 4,457
  • 2
  • 20
  • 59