gpt4 book ai didi

Godot:调用外部方法

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

大量的谷歌搜索,我仍然没有掌握可能是一个简单的解决方案。
场景:“主要”。包含一个 TileMap“Grid”,并附有一个脚本“Grid.gd”。
场景:“玩家”。包含一个带有脚本的 KinematicBody2D“播放器”“Player.gd”
在 Player.gd 中,我需要调用 Grid.gd 中的一个方法“_Calculate”,将两个变量传递给它,并让它返回一个变量。

var vNewPosition = Grid._Calculate(vPlayer, vInputDirection)


错误:标识符“Grid”未在当前范围内声明。
显然,我需要在某处引用 Grid.gd 脚本来访问它,但是我尝试过的许多示例都不起作用。
提前致谢,
乔希

最佳答案

鉴于

The Main scene has an instance of the Player scene



In Player.gd, I need to call a method in Grid.gd "_Calculate", pass it two variables, and have it return one variable.


我会给你几个选择。

糟糕的方式
如果 Player 知道到 Grid 的节点路径,它可以使用 get_node为拿到它,为实现它。
onready var _grid = get_node("../../grid")
或类似的东西。
然后使用它:
var vNewPosition = _grid._Calculate(vPlayer, vInputDirection)
这种方法当然是 不推荐 .如果节点路径错误,它将中断。

常见的方式
假设 Player 不知道节点路径(更有可能),您可以导出 NodePath Player.gd 中的变量并使用它来获取网格:
exprort var grid_path:NodePath
onready var _grid = get_node(grid_path)
然后需要将Main场景中的Grid Path属性设置为Grid。
这种方法比前一种方法更好,因为它不依赖于到 Grid 的路径。然而,它仍然取决于存在的网格。如果没有 Grid 时 Player 没有意义,这种方法是可以的。

好办法
如果 Grid 可能存在也可能不存在,并且我们希望 Player 能够正常工作,我们可以调整上述方法:
exprort var grid_path:NodePath
onready var _grid = get_node_or_null(grid_path)
并记得在使用之前检查 grid 是否为空:
if grid == null:
return # or whatever

var vNewPosition = grid._Calculate(vPlayer, vInputDirection)
或者像这样:
var vNewPosition = grid._Calculate(vPlayer, vInputDirection) if grid != null else null
这也允许我们指定一个默认值 vNewPosition当没有网格时将采用(行尾的 null)。因此,当没有 Grid 时,您可以让 Player 工作,当有它时,它就会使用,无论在哪里(因为 Main 告诉它它在哪里)。
这个方案并没有完全解耦,因为Player还是知道 grid是一个有 _Calculate 的东西.我们还假设有零个或一个,而不是多个。我可以想到一种方法来解决这个问题,但是为了解耦而解耦是不必要的。我认为这对您的用例来说已经足够好了。但是,如果您想要过度设计的方式,请告诉我。

关于Godot:调用外部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67654904/

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