改变位置时如何调用函数?
我试图在每次 position2D
节点的位置发生更改时调用一个函数
我尝试重写 文档 像这样:
extends Position2D
tool
func set_position(value):
print("changed position ",value)
self.position=value;
我在这里缺少什么?有没有办法实现我正在尝试的目标?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
set_position
方法不是虚拟的。你并没有推翻它。充其量你只是隐藏它。如果您想遵循这种方法,请使用
_set
(请注意,文档提到_set
是虚拟的)。我们的想法是,我们将尝试设置position
,在设置后做任何我们想做的事情,然后让它正常继续。您应该看到,当您在检查器面板中修改
position
时,您会收到消息。我怀疑这对你来说还不够。特别是,上述解决方案不会检测
position
何时发生变化,因为您在编辑器中拖动Position2D
。这是因为当您在编辑器中移动
Position2D
时,Godot 没有设置position
属性。相反,它(在深入研究源代码之后)调用未记录的方法_edit_set_position
...您也可以从 GDScript 调用它!无论如何,重点是我们无法拦截它(并且我们无法覆盖它。是的,我尝试过)。相反,我们将使用
_notification
。我们正在寻找NOTIFICATION_TRANSFORM_CHANGED
,但要获取该通知,我们需要使用set_notify_transform
启用它。代码如下所示:通过这种方法,当用户通过拖动或使用键盘方向键在编辑器中移动
Position2D
时,您还可以做出反应。 Godot 在哪些情况下使用_edit_set_position
。或者我们无法用初始方法拦截的任何其他方式。如果您需要在每次
Node2D
移动时执行某些操作,但它移动得并不频繁,则可以使用此方法。顺便说一句,这也适用于 3D。
The method
set_position
is not virtual. You are not overriding it. At best you are hiding it.If you want to follow that approach, intercept the property instead, using
_set
(Notice that the documentation mentions that_set
is virtual). The idea is that we are going to take the attempt to setposition
, do whatever we want to do when it is set, and then let it continue normally.And you should see that when you modify the
position
in the inspector panel, you get the message.I suspect that is not enough for you. In particular the above solution does not detect when the
position
changes because you drag thePosition2D
in the editor.This is becase when you move the
Position2D
in the editor, Godot is not setting theposition
property. Instead it is (after digging in the source code) calling the undocumented method_edit_set_position
… Which you can also call from GDScript! Anyway, the point is we cannot intercept it (and we cannot override it. Yes, I tried).Instead we are going to use
_notification
. We are looking forNOTIFICATION_TRANSFORM_CHANGED
, but to get that notification we need to enable it withset_notify_transform
. The code looks like this:With this approach you will also be able to react to when the user moves the
Position2D
in the editor by dragging it around or with the keyboard directional keys. Which are the cases where Godot uses_edit_set_position
. Or any other means that we could not intercept with the initial approach.You can use this approach if you need to do something every time the
Node2D
moves, but it does not move very often.By the way, this also works for 3D.