请注意,我使用的是javafx库。以下是通过空间移动的类船的功能。玩家点击船只,出现一个下拉菜单,点击“移动”后,一个协程开始\ moveJob \调用函数\ move()\,这将使对象开始向目的地移动。
问题在于,如果我再次单击“移动”,中途航行,那么对象将表现不正常,因为两个协同程序将同时运行并更新对象的x和y坐标。
因此我需要取消\ moveJob \每次我点击“移动”并开始一个新目的地的新协程。我还没想出如何使用\ movingJob.cancel()\ preemptively来说,以防有一个协程已经运行。
item1.setOnAction {
println("Something...")
root.onMouseClicked = EventHandler { event ->
launch {
println("Clicked on an object.")
}
/* If you click on an object, you don't want scene.onMouseClicked
to be executed. event.consume() gobbles the event so that it isn't passed
down.
*/
event.consume()
// Here we should have something that reaches
root.onMouseClicked = null
scene.onMouseClicked = null
}
scene.onMouseClicked = EventHandler { event ->
val moveJob =launch {
move(event, root)
}
root.onMouseClicked = null
scene.onMouseClicked = null
}
/* Move to coorindates that the user clicks next */
}
答案 0 :(得分:0)
在班级的某处声明Job
变量
private var currentJob: Job? = null
并使用以下代码
item1.setOnAction {
println("Something...")
root.onMouseClicked = EventHandler { event ->
currentJob?.cancel()
currentJob = launch {
println("Clicked on an object.")
}
/* If you click on an object, you don't want scene.onMouseClicked
to be executed. event.consume() gobbles the event so that it isn't passed
down.
*/
event.consume()
// Here we should have something that reaches
root.onMouseClicked = null
scene.onMouseClicked = null
}
scene.onMouseClicked = EventHandler { event ->
currentJob?.cancel()
currentJob = launch {
move(event, root)
}
root.onMouseClicked = null
scene.onMouseClicked = null
}
/* Move to coorindates that the user clicks next */
}