set_global_position设置位置为错误值

问题描述 投票:0回答:1

[嘿,我有一个函数,将KinematicBody2D的(播放器)主体放置在Node2D(门户)的旁边。 2个入口链接在一起,当玩家在场景A中进入入口X时,它们将放置在场景B中相应入口X的旁边,反之亦然。这是函数:

func fix_player_position(entry_portal_link_id):
    var pos = exit_positions[entry_portal_link_id]
    var new_pos: Vector2
    print("Current entry points for ")
    print(exit_positions)
    $player.set_global_position(Vector2(0,0))
    print("Player's position before change: " + str($player.get_global_position()))

    if portal_list[entry_portal_link_id].landing_point == Direction.Up:
        new_pos = Vector2(pos.x, pos.y-64)
    elif portal_list[entry_portal_link_id].landing_point == Direction.Down:
        new_pos = Vector2(pos.x, pos.y+64)
    elif portal_list[entry_portal_link_id].landing_point == Direction.Left:
        new_pos = Vector2(pos.x-64, pos.y)
    elif portal_list[entry_portal_link_id].landing_point == Direction.Right:
        new_pos = Vector2(pos.x+64, pos.y)
    $player.set_global_position(new_pos)
    print(pos)
    print(new_pos)
    print($player.get_global_position())

这里我们获得Node2D的位置,将播放器(KinematicBody2D)的位置重置为(0,0),根据我们要放置KinematicBody2D的哪一侧应用偏移,然后设置新位置并打印出所有位置。但是,它不能正常工作。这是最后的输出

Current entry points for 
{house_link1:(-3807.48999, 11041.799805), house_link2:(-4132.839844, 10655)} # We store the positions in a dictionary using the portal ID
Player's position before change: (-26252.199219, 11936) # This is supposed to be (0,0)
(-4132.839844, 10655) # The pos variable, i.e the stored position of the Node2D
(-4132.839844, 10719) # The new_pos, i.e. the intended position of the character
(-30385.039062, 22655) # The position of the character after setting

#注释是我添加的,以澄清正在打印的内容。如您所见,set_global_position调用未正确设置位置。但是,它确实可以在其他场景中正确设置玩家的位置。

场景A->场景B,正常工作

场景B->场景A,突然无法正常工作。

如您所见,我在这里有点迷惑,这是gdscript本身的错误吗?还是我是个白痴,做错了什么?

这里是从场景A->场景B->场景A的完整输出

Current entry points for 
{house_link1:(32, -288), house_link2:(-355.494995, -477.505005)}
Player's position before change: (0, 0)
(-355.494995, -477.505005) # pos
(-355.494995, -413.505005) # new_pos
(-355.494995, -413.505005) # players position

Current entry points for 
{house_link1:(-3807.48999, 11041.799805), house_link2:(-4132.839844, 10655)}
Player's position before change: (-26252.199219, 11936)
(-4132.839844, 10655) # pos
(-4132.839844, 10719) # new_pos
(-30385.039062, 22655) # players_position
godot gdscript
1个回答
0
投票

所以我不确定实际的问题是什么,但是解决方案是更换

$player.set_global_position(new_pos)

with

$player.position = new_pos

并且代码成功运行。

© www.soinside.com 2019 - 2024. All rights reserved.