0

So i'm creating a tile based game and currently working on hovering on tiles i have the hovering sorted so that when you hover over an image it changes colour but i am stuck with how to remove the colour when the next tile is hovered upon.

Tile previous;
public void CheckHover() {
    for (Tile t  : map.getTiles()) {
        if (t.IsMouseOver(screen.getMousePosition().x, screen.getMousePosition().y)) {
            t.setMouseOver(true);
            if (previous == null) {
                previous = t;
            } else {
                previous.setMouseOver(false);
            }
        }
    }
}

My code above does not quite work i believe it may be down to how i am referencing the object but if i am doing a for each loop how can i get object that is currently hovered and setMouseOver to false?

James Young
  • 313
  • 3
  • 10
  • 19

2 Answers2

0

I assume you store previous somewhere in the class that contains CheckHover() (btw, check the naming conventions, it should better be checkHover()).

Thus you need to update previous whenever the mouse is over a different tile.

Here's some pseudocode for your loop:

boolean hovering = false;
for( Tile t : tiles ) {
  if( t.mouseOver(...) ) {
    //assuming t is never null, t.equals(...) will also work if previous is null
    if ( !t.equals( previous ) ) {
      if( previous != null ) {
        previous.setMouseOver(false);
      }
      previous = t;
    }
    //else nothing to do, still hovering over the same tile

    hovering = true;
    break; //no need to look further
  }
}

//reset when not hovering over any tile anymore
if( !hovering && previous != null ) {
  previous.setMouseOver(false);
  previous = null;
}
Thomas
  • 87,414
  • 12
  • 119
  • 157
0

Two suggestions:

  1. Learn How to Write a Mouse Listener - You will definitely need to know this; particularly the mouseEntered() and mouseExited() methods. If you don't need all the methods of the MouseListener interface, you can extend the MouseAdapter abstract class and overriding those two methods I mentioned.
  2. Learn How to Use Layered Panes - I think you can take advantage of layered panes to achieve what you want by giving the appearance that the tile has changed colors when the above mouse events are triggered.

UPDATE:

I found this Stackoverflow post that might be exactly what you need to do. Go there and try the suggested code and try to adapt it to what you are trying to do. I believe it will work great for your particular case.

Community
  • 1
  • 1
hfontanez
  • 5,774
  • 2
  • 25
  • 37