I'm trying to detect when a mouse is hovering an image (Play Image) and when I'm clicking the mouse something happens.
I draw an image on the center of the screen and I don't know how to implement this on my own code:
@Override
public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException {
f = (float) (0.1 * Main_Activity.apg.getHeight() / 180);
play = new Image("res/play_image.png");
play_Original_Width = play.getWidth();
play_Original_Height = play.getHeight();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
width = screenSize.getWidth();
height = screenSize.getHeight();
}
@Override
public void render(GameContainer arg0, StateBasedGame arg1, Graphics g) throws SlickException {
play.draw(Main_Activity.apg.getWidth() / 2 - ((play_Original_Width * f) / 2),
Main_Activity.apg.getHeight() / 2 - ((play_Original_Height * f) / 2), f);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int arg2) throws SlickException {
int x = Mouse.getX();
int y = Mouse.getY();
}
apg:
apg = new AppGameContainer(new Main_Activity(game_Name));
apg.setDisplayMode((int) width, (int) height, false);
apg.setShowFPS(false);
apg.start();
How can I manage to detect when the mouse is hovering the image (Play Image)?
Thanks in advanace.
You just have to test if your x value is between your Image X and Image X + image width, and same for your y value.
In your update method :
int x = Mouse.getX();
int y = Mouse.getY();
int playX = Main_Activity.apg.getWidth() / 2 - ((play_Original_Width * f) / 2);
int playY = Main_Activity.apg.getHeight() / 2 - ((play_Original_Height * f) / 2);
if (x > playX && x < playX+play_Original_Width && y > playY && y < playY + play_Original_Height) {
// then your mouse coordinates are over your image.
}
Additional (use if useful to you):
In some personal code, I used to implement a ImageRectangle that inherits from Rectangle and contains an Image. With this behaviour I could use the method intersects
to detect this over. And I prefer using a mouseListener to manage these mouse event.
public ImageRectangle extends Rectangle {
Image play;
public ImageRectangle(Image,x,y,f){...}
public void init(...){...}
public void render(...){this.image.draw();}
public void update(...){...}
}
In your mouseMoved method :
Rectangle mousePosition = new Rectangle(x,y,1,1);
if(mousePosition.intersects(playImageRectangle)) {//do whatever you need}