首页 > 解决方案 > 每当我的角色转身时,运动脚本就不会前进

问题描述

我将这个移动脚本附加到我的播放器上,但是每当我转动例如 90 度时,如果我按下 w,它就不会前进,现在我知道这是因为 z 不同,因为我移动了相机但是我该如何解决这个问题?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{

public Rigidbody rb;
float forwardForce = 500f;
float sidewaysForce = 500f;
float jumpForce = 100f;
// Start is called before the first frame update
// Update is called once per frame
public Vector3 jump;

public bool isGrounded;
void Start()
{
    rb = GetComponent<Rigidbody>();
}
void OnCollisionStay()
{
    isGrounded = true;
}


void FixedUpdate()
{
    if (Input.GetKey("d"))
    {
        rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("a"))
    {
        rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("w"))
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);
    }
    if (Input.GetKey("s"))
    {
        rb.AddForce(0, 0, -forwardForce * Time.deltaTime);
    }

    if (Input.GetKey("space") && isGrounded)
    {

        rb.AddForce(0, jumpForce, 0);
        isGrounded = false;

    }
}
}

标签: c#unity3d

解决方案


AddForce使用世界空间。因此,无论您的对象如何旋转,它都将始终沿 Unity 全局 X、Y、Z 轴施加力。

您想使用AddForceRelativewhich 解释该对象的局部空间中的给定值(因此使用其自己的 X、Y、Z 轴)

相对于其坐标系向刚体添加力。

void FixedUpdate()
{
    if (Input.GetKey("d"))
    {
        rb.AddForceRelative(sidewaysForce * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("a"))
    {
        rb.AddForceRelative(-sidewaysForce * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey("w"))
    {
        rb.AddForceRelative(0, 0, forwardForce * Time.deltaTime);
    }
    if (Input.GetKey("s"))
    {
        rb.AddForceRelative(0, 0, -forwardForce * Time.deltaTime);
    }

    if (Input.GetKey("space") && isGrounded)
    {
        // Here you most probably would want to keep the global UP direction ;)
        rb.AddForce(0, jumpForce, 0);
        isGrounded = false;
    }
}

通常,您可能希望使用与相机不同的对象进行移动。

为什么?

因为否则

  • 如果你的相机向下看并且你按下 W -> 你向下添加一个力,这样试图将玩家压入地面
  • 如果您的相机向上看并且您按 W -> 您会向上添加一个力,因此根据您的力的强度,这可能会使玩家四处飞行^^

所以我宁愿使用像这样的层次结构

Player (This one receives the movement WASD + ONLY global Y-axis rotation)
|--Camera (This one receives ONLY local X-axis rotation)

当然,您可以在一个脚本中处理这两种情况,但您应该在其中应用给定的输入。这样,它Player实际上永远不会向下或向上看,因为它只会围绕全局 Y 轴旋转(向左和向右看)。

相机是唯一向下和向上看的东西,但我们不使用它的局部空间进行运动,而是使用其中之一,Player因此相机方向对运动无关紧要。


推荐阅读