我正在开发的游戏是你从病毒捍卫细胞,我需要的精灵有一个MouseListener
的时候,鼠标点击该sprite
,它会被破坏,我不知道如何获得的位置鼠标并将其应用于精灵。
基本上,我需要抓住mouse
和sprite
的位置,当用户点击它将重置sprite
。
我试图做这个debugging,所以就像鼠标hover在精灵的位置,它会打印一个消息“hover”,但它不工作。
对于我的更新方法,我补充道:
if(MouseInfo.getPointerInfo().getLocation() == this.getLocation()) System.out.println("SAME LOCATION");
我甚至打印出精灵和鼠标的位置,我把它们都alignment到0
,但它仍然不起作用。
结论:
如何检查鼠标的位置是否与Sprite相同,然后将消息打印到控制台?
如果我正确理解你的方法和问题,你应该使用下面的algorithm:
Obtain the minimum and maximum coordinates of the sprite. Obtain the position of the mouse pointer. Test both axes within a range.
第一个需要精灵的尺寸和位置。 假设它的位置相对于精灵的左上角。 伪代码看起来像这样(我的Java是生锈的):
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. }