【问题标题】:I want my character to move only in the direction that it is looking我希望我的角色只朝它正在看的方向移动
【发布时间】:2019-11-06 19:41:58
【问题描述】:

我有一个 3D 游戏,我的相机正在观察我的所有地形,并且我有一个使用 Xbox 控制器移动的角色。我希望我的角色只向它所看的方向移动,而不是向两侧移动。我有下一个让我的角色移动的代码。

void Update()
    {
        MoveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        moveVelocity = MoveInput * MoveSpeed;

        Vector3 PlayerDirection = Vector3.right * -Input.GetAxisRaw("RHorizontal") + Vector3.forward * -Input.GetAxisRaw("RVertical");
        if (PlayerDirection.sqrMagnitude > 0.0f)
        {
            transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
        }

角色随着控制器的左侧移动,而右侧则可以移动所面对的方向。

【问题讨论】:

  • 您找到解决方案了吗?

标签: c# unity3d


【解决方案1】:

目前,您将输入用作世界空间方向的 x 和 z 分量。它根本不考虑角色的旋转。

相反,您应该将输入与世界空间中相应的局部方向相乘,然后将它们组合起来。在您的情况下,这可能如下所示:

MoveInput = (
        transform.right * Input.GetAxisRaw("Horizontal") 
        + transform.forward * Input.GetAxisRaw("Vertical")
        ).normalized;

moveVelocity = MoveInput * MoveSpeed;

Vector3 PlayerDirection = Vector3.right * -Input.GetAxisRaw("RHorizontal") 
        + Vector3.forward * -Input.GetAxisRaw("RVertical");

if (PlayerDirection.sqrMagnitude > 0.0f)
{
    transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
}

normalized 是为了让你不会在对角线上移动得更快。

【讨论】:

    【解决方案2】:

    我找到了解决办法,代码如下:

    MoveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
    
    moveVelocity = MoveInput * MoveSpeed;
    
    Vector3 PlayerDirection = Vector3.right * Input.GetAxisRaw("Horizontal") + Vector3.forward * Input.GetAxisRaw("Vertical");
    if (PlayerDirection.sqrMagnitude > 0.0f)
    {
        transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2015-04-29
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多