1
\$\begingroup\$

The game I am developing is in which you defend the Cell from the Viruses, and I need the sprites to have a MouseListener for when the mouse clicks on that sprite, it will get destroyed, and I cannot figure out how to get the location of the mouse and apply it to the sprite.

Basically, I need to grab the location of the mouse and the sprite, and when the user clicks it will reset the sprite.

I have tried to do debugging with this, so like if the mouse hovers the location of the sprite it will print a message "Hovering" but it just doesn't work.

For my update method, I added:

if(MouseInfo.getPointerInfo().getLocation() == this.getLocation()) System.out.println("SAME LOCATION");

I even got it to print out the location of the sprite and the mouse, and I aligned them both to 0,0 and it still didn't work.

CONCLUSION:
How do I check if the location of the mouse is the same as a sprite, and then print out a message to the console?

\$\endgroup\$
1
\$\begingroup\$

If I understand your approach and problem correctly, you should use the following algorithm:

Obtain the minimum and maximum coordinates of the sprite.
Obtain the position of the mouse pointer.
Test both axes within a range.

The first requires the dimensions of the sprite and it's position. Let's say its position is relative to the top-left of the sprite. Pseudo-code would look like this (my Java is rusty):

int minx = this.getPosition().x();
int miny = this.getPosition().y();
int maxx = minx + this.getWidth();
int maxy = miny + this.getHeight();

int mousex = MouseInfo.getPointerInfo().getLocation().x();
int mousey = MouseInfo.getPointerInfo().getLocation().y();

if ((mousex >= minx && mousex <= maxx) && (mousey >= miny && mousey <= maxy) {
    System.out.println("Clicked on the sprite.");
    // Some reset code.
}
\$\endgroup\$
1
  • \$\begingroup\$ Yes this does work, thank you for that! The only error that occurs is that the mouse gets the screen locations, and not the JFrame locations. How would I add into the method to get the literal location on the screen? \$\endgroup\$ – Shzylo Oct 1 '13 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.