【问题标题】:Changing the player's position in Update() or FixedUpdate() method?在 Update() 或 FixedUpdate() 方法中更改玩家的位置?
【发布时间】:2019-08-07 13:41:12
【问题描述】:

在我的游戏中,当玩家触摸特定 GameObject 的对撞机并且玩家按下 X 键时,我想将他的位置更改为另一个 游戏对象

为此,我使用以下代码

void FixedUpdate()
{
    if (Input.GetKeyDown(KeyCode.X))
    {
        // Check Colliders collition
        // End of Check Colliders collition

        var playerRigidBody = GetComponent<Rigidbody2D>();
        playerRigidBody.position = AnotherObject.transform.position;
    }
}

我意识到,当我按下 X 键时,玩家经常不会将他的位置更改为另一个 GameObject 的位置。但是,如果我将代码移动到 Update() 方法,它会按预期工作(没有延迟)。

但是我在官方文档和很多博客中读到物理和刚体相关的代码必须放在FixedUpdate而不是Update

所以问题如下:

对于这种情况,不建议将代码放在 Update() 方法中? (请注意,我没有使用力或扭矩)

如果不推荐,那么我如何确保每次玩家按下 X 键时,他都会将他的位置更改为 FixedUpdate() 中的另一个 GameObject 位置?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    一般来说,如果你想要一个平稳的运动,你应该在FixedUpdate 中使用MovePosition,否则关于物理的所有事情(还有 RigidBody)你应该总是在FixedUpdate 中进行(正如那里的 API 中所解释的那样)。


    但是,您应该在Update 中捕获GetKeyDown拆分这两件事

    bool wasClicked;
    RigidBody playerRigidBody;
    
    void Start()
    {
        // do this only once!
        playerRigidBody = GetComponent<Rigidbody2D>();
    }
    
    void Update()
    {
        // Catch user input here
    
        if (Input.GetKeyDown(KeyCode.X))
        {
            wasClicked = true;
        }
    }
    
    void FixedUpdate()
    {
        // Handle physics here
    
        if(!wasClicked) return;
    
        playerRigidBody.position = AnotherObject.transform.position;
    
        wasClicked = false;
    }
    

    【讨论】:

    • 请注意,对于 teleportation (if the player is touching the collider of a specific GameObject and the player press the X key I want to change his position to the position of another GameObject) 不需要 MovePosition。
    • @Draco18s 感谢您的帮助。我有一个错误,我正在战斗一周。解决方案是在 Update()FixedUpdate() 方法中拆分代码。再次感谢您!
    • @vcRobe 哦,毫无疑问。只是有时你确实想传送玩家,但在这种情况下使用 MovePosition 将不起作用!
    • 刚刚添加了MovePosition 作为附加的一般性评论。正如您在代码示例中看到的那样,无论如何我都使用了rigidbody.position ;)
    • 抱歉,在之前的评论中我感谢@derHugo。无论如何,Draco18s 谢谢你的评论。在怀疑 Update()FixedUpdate() 方法之前,我花了几个小时猜测为什么玩家没有传送到预期的位置,这是因为我使用了 RidigBody2D.MovePosition() 而不是 RigidBody2D.position 但我修复了它,因为我在测试中传送玩家的距离很长,显然玩家的最终位置总是错误的。谢谢你们!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多