繁体   English   中英

Slick2D-检测图像上的鼠标悬停

[英]Slick2D - Detect mouse hover on an Image

我试图检测鼠标何时将鼠标悬停在图像(播放图像)上,以及单击鼠标时发生了什么情况。

我在屏幕中央绘制了一个图像,但我不知道如何在自己的代码中实现该图像:

    @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();

如何管理鼠标悬停在图像上的时间(播放图像)?

谢谢。

您只需要测试x值是否介于Image X和Image X +图像宽度之间,以及是否与y值相同。

在您的更新方法中:

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.
}

其他(如果对您有用,请使用):

在某些个人代码中,我曾经实现过一个ImageRectangle,它继承自Rectangle并且包含一个Image。 通过这种行为,我可以使用方法intersects来检测这种情况。 而且我更喜欢使用mouseListener来管理这些鼠标事件。

public ImageRectangle extends Rectangle {
    Image play;
    public ImageRectangle(Image,x,y,f){...}
    public void init(...){...}
    public void render(...){this.image.draw();}
    public void update(...){...}
}

mouseMoved方法中:

Rectangle mousePosition = new Rectangle(x,y,1,1);
if(mousePosition.intersects(playImageRectangle)) {//do whatever you need}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM