Godot中如何单独修改场景实例内Sprite的可见性?
解决井字棋方块点击全亮问题
问题出在你的_input函数上——这是全局输入监听函数,任何地方按下鼠标左键,所有playable square实例都会执行theX.visible=true,所以所有X都会同时显示。
正确的两种解决方式:
方式1:使用Area2D的input_event信号(推荐)
Area2D自带专属交互信号,只有当鼠标在当前方块的碰撞范围内操作时才会触发,无需全局监听:
- 打开
playable square场景,选中根节点Area2D - 在右侧信号面板找到
input_event信号,点击连接并绑定到脚本的新函数 - 修改脚本如下:
extends Area2D @onready var theX = $TheX @onready var theO = $TheO # 修正你之前的拼写错误:The0 → TheO func _on_input_event(viewport, event, shape_idx): # 判断是否为鼠标左键按下事件 if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed: theX.visible = true func playO(): # 函数名规范:play0 → playO theO.visible = true
方式2:在_input中判断鼠标归属
如果坚持使用_input,需要额外检查鼠标位置是否属于当前实例的碰撞区域:
extends Area2D @onready var theX = $TheX @onready var theO = $TheO func _input(event): if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed: # 验证鼠标全局位置是否在当前方块的范围内 if get_global_rect().has_point(get_global_mouse_position()): theX.visible = true func playO(): theO.visible = true
额外注意事项
- 必须修正脚本中
$The0的拼写错误,否则会出现节点找不到的报错 - 每个
playable square实例的脚本都是独立运行的,只要触发逻辑仅针对当前实例,就不会出现全局触发的问题
内容的提问来源于stack exchange,提问作者tutiplain
相关产品推荐
相关产品推荐

