【问题标题】:Player not moving in Unity玩家在 Unity 中不动
【发布时间】:2019-12-08 11:46:48
【问题描述】:

这是我的代码:

using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    // This is a reference to the Rigidbody component called "rb"
    public Rigidbody rb;

    public float forwardForce = 4000f;
    public float sidewaysForce = 100f;

    // We marked this as "Fixed"Update because we
    // are using it to mess with physics.   
    void FixedUpdate()
    {
        // Add a forward force
        rb.AddForce(0, 0, forwardForce * Time.deltaTime); 

        if( Input.GetKey("d") )
        {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }

        if( Input.GetKey("a") )
        {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
    }
}

Unity - Player not moving

请帮忙。

【问题讨论】:

  • 附加一个屏幕截图,选择你的玩家对象,我们的rigidBody组件在Inspector中可见,你的玩家在场景和游戏视图中是焦点。
  • 在您尝试时确保游戏视图聚焦。否则,输入将不会被捕获。

标签: c# visual-studio unity3d


【解决方案1】:

让我们尝试一些事情。首先,尝试在 FixedUpdate 中取出 Time.deltaTime。在 FixedUpdate 中添加力时,通常不需要使用Time.deltaTime。

其次,尝试创建零摩擦的物理材质并将其附加到玩家对象的盒子碰撞器。

【讨论】:

【解决方案2】:

您需要移动您的逻辑以获取Update() 方法的输入。从那里,您可以设置力的值,然后将此力添加到 FixedUpdate() 中的 RigidBody。这样,我们就可以确保每一帧都检测到获取输入的逻辑。

private float movement = 0f;

void Update()
{
    if( Input.GetKey("d") )
    {
        movement = sidewaysForce;
    }
    else if ( Input.GetKey("a") )
    {
        movement = -sidewaysForce;
    }
    else
    {
        movement = 0f;
    }
}

void FixedUpdate()
{
    rb.AddForce(0, 0, forwardForce * Time.fixedDeltaTime); 

    rb.AddForce(movement * Time.fixedDeltaTime, 0, 0, ForceMode.VelocityChange);
}

我还将Time.deltaTime 更新为Time.fixedDeltaTime,因为您在FixedUpdate() 中调用它。

最后,您可能希望在添加侧向力时使用不同的力模式进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多