gpt4 book ai didi

JAVA - Graphics2D 根据 mouseEvent 确定游戏中可能的移动

转载 作者:行者123 更新时间:2023-12-01 12:20:37 24 4
gpt4 key购买 nike

我正在开发一个基于鼠标事件的游戏,类似于:How to draw grid using swing class Java and detect mouse position when click and drag

我目前陷入困境,试图确定我在网格中指向的 block 是否允许移动。

最佳答案

如果您只是想知道鼠标是否在“允许的”单元格内,您可以将 MouseListener 修改为...

MouseAdapter mouseHandler = new MouseAdapter() {

// detects when mouse was moved
public void mouseMoved(MouseEvent e) {
int width = getWidth(); // gets screen resolution e.g. 640x 480
int height = getHeight();
// System.out.println(width + " x " +height );

int cellWidth = width / columnSize; // size of the cell in pixels e.g 32x24
int cellHeight = height / rowSize;
// System.out.println(cellWidth + " x " +cellHeight );

int column = e.getX() / cellWidth; // gets specific cell e.g. (14,14)
int row = e.getY() / cellHeight;
// System.out.println("col " +column + " " + row);

// This is the x/y position of the mouse when the event
// was triggered
Point mp = e.getPoint();
for (Rectangle cell : allowedCells) {
if (cell.contains(mp)) {
// Do what ever you want to do here...
}
}

selectedCell = new Point(column, row); // point to represent xy location
repaint(); // repaint forest
}
};

关于JAVA - Graphics2D 根据 mouseEvent 确定游戏中可能的移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com