GUT测试中调用KinematicBody2D的get_position报get_global_transform错误
概述
我尝试使用GUT为GDScript中的player节点编写单元测试,该节点属于KinematicBody2D类型,调用其get_position()方法时触发如下错误:
ERROR: get_global_transform: Condition "!is_inside_tree()" is true. Returned: get_transform() At: scene/2d/canvas_item.cpp:467. ERROR: body_test_motion: Condition "!body->get_space()" is true. Returned: false At: servers/physics_2d/physics_2d_server_sw.cpp:1046. ERROR: get_global_transform: Condition "!is_inside_tree()" is true. Returned: get_transform() At: scene/2d/canvas_item.cpp:467. ERROR: body_test_ray_separation: Condition "!body->get_space()" is true. Returned: false At: servers/physics_2d/physics_2d_server_sw.cpp:1058.
预期表现
我预期在_physics_process()执行后可以获取到player更新后的position,但实际返回值为Vector2(0, 0)。
参考资源
我是首次使用GDScript,编写该测试时参考了以下资料:
- 8-way movement
- TDD and PONG Episode 1
- GUT Command-line
- Stubbing Input Class
已尝试的无效解决方案
我猜测需要将player挂载为其他节点的子节点,但不清楚如何在测试中实现该操作。
我检索了Gut issues中关于测试内使用add_child()的内容,未找到对应解决方案。
我还尝试将player挂载为Area2D的子节点,也没有生效,代码如下:
var player := Player.new(input) var area := Area2D.new() area.add_child(player)
相关代码
以下是命令行调用gut时触发错误的对应代码:
test/unit/actors/test_player.gd
extends "res://addons/gut/test.gd" func test_can_create_player() -> void: var input = MockInput.new() var player := Player.new(input) assert_not_null(player) func test_can_move_player_up() -> void: var input = MockInput.new() input.press("ui_up") var player := Player.new(input) simulate(player, 1, .1) assert_eq(player.get_position(), Vector2(200, 0))
test/mock_input.gd
class_name MockInput var _pressed: Dictionary = {} func press(key: String) -> void: _pressed[key] = true func release(key: String) -> void: _pressed[key] = false func is_action_pressed(key: String) -> bool: if _pressed.has(key): return _pressed.get(key) return false
entities/actors/player.gd
extends KinematicBody2D class_name Player export var speed: int = 200 var _input: Object = Input var _velocity: Vector2 = Vector2() func _init(input: Object = Input): _input = input func _physics_process(_delta: float) -> void: _velocity = Vector2() if _input.is_action_pressed("ui_right"): _velocity.x += 1 if _input.is_action_pressed("ui_left"): _velocity.x -= 1 if _input.is_action_pressed("ui_down"): _velocity.y += 1 if _input.is_action_pressed("ui_up"): _velocity.y -= 1 _velocity = _velocity.normalized() * speed _velocity = move_and_slide(_velocity)
内容的提问来源于stack exchange,提问作者SpeedyLom
相关产品推荐
相关产品推荐

