gpt4 book ai didi

java - 使用 JNativeHook 制作游戏

转载 作者:行者123 更新时间:2023-11-29 08:34:28 31 4
gpt4 key购买 nike

我正在为 PC 游戏开发一个简单的叠加程序。它只是一个位于屏幕中央的透明矩形,但其大小由用户的鼠标滚轮控制。所以这个概念是简单地将透明矩形的大小与敌方玩家的大小相匹配来计算他的距离。

不幸的是,我无法使用传统的鼠标监听器实现这一点,因为鼠标必须同时关注游戏和覆盖程序。我正在尝试 JNativeHook,但我无法更新我的矩形。有什么建议吗?

public class Main extends Application implements NativeMouseWheelListener {

Rectangle r = new Rectangle();
int y = 540;
int width = 75;
int height = 180;
int velocity = 10;

@Override
public void start(Stage stage) throws Exception {
AnchorPane root = new AnchorPane();
r = rect();
root.getChildren().add(r);
root.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");

Scene scene = new Scene(root, 1920, 1080);
scene.setFill(null);

stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.setX(0);
stage.setY(0);
stage.show();
stage.setAlwaysOnTop(true);
}

public void nativeMouseWheelMoved(NativeMouseWheelEvent e) {
int direction = e.getWheelRotation();
System.out.println("Mouse Wheel Moved: " + direction);
r.setY(r.getY() + direction);
}

public Rectangle rect() {
r.setWidth(width);
r.setHeight(height);
r.setX(960 - (width/2));
r.setY(540);
r.setFill(Color.TRANSPARENT);
r.setStroke(Color.BLACK);
return r;
}

public static void main(String[] args) {
go();
launch(args);
}

public static void go() {
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
ex.printStackTrace();
System.exit(1);
}

GlobalScreen.getInstance().addNativeMouseWheelListener(new Main());
}
}

最佳答案

我强烈建议采用@vince-emigh 的建议,并通过使用 AbstractExecutorService 的自定义实现在与您的 ui 环境相同的线程上运行 JNativeHook,如下所示。

public class JavaFxDispatchService extends AbstractExecutorService {
private boolean running = false;

public JavaFxDispatchService() {
running = true;
}

public void shutdown() {
running = false;
}

public List<Runnable> shutdownNow() {
running = false;
return new ArrayList<Runnable>(0);
}

public boolean isShutdown() {
return !running;
}

public boolean isTerminated() {
return !running;
}

public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return true;
}

public void execute(Runnable r) {
Platform.runLater(r);
}
}

然后使用该类作为事件派发器:

// Set the event dispatcher to a swing safe executor service.
GlobalScreen.setEventDispatcher(new JavaFxDispatchService());

// Initialize native hook.
try {
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
ex.printStackTrace();
System.exit(1);
}

GlobalScreen.addNativeKeyListener(this);

有关详细信息,请参阅 wiki 中的线程安全文章

关于java - 使用 JNativeHook 制作游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403575/

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