首页 > 解决方案 > 如何限制玩家在空中移动时移动?

问题描述

我对 Unity 中的 GameDev 非常陌生,需要帮助解决玩家移动问题。我的动作设置方式,让你在半空中转身和移动,这给人一种不切实际的感觉。我想知道一旦你跳到一个方向,我将如何让它到达哪里,直到你回到地面你才能改变它。

我知道它应该只是一个简单的布尔值来检查玩家是否在空中,我只是不知道如何在我当前的移动脚本中对其进行编码。谢谢。

using System.Collections;

使用 System.Collections.Generic;使用 UnityEngine;

公共类 PlayerMovement : MonoBehaviour { Vector3 速度;

public float speed = 12f;
public float gravity = -9.81f;
public CharacterController controller;
public float jumpHeight = 3f;

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;

bool isGrounded;

// Update is called once per frame
void Update()
{
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if(isGrounded && velocity.y < 0)
    {
        velocity.y = -2f;
    }

    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;

    controller.Move(move * speed * Time.deltaTime);

    if(Input.GetButtonDown("Jump") && isGrounded)
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);
}}

标签: c#unity3d

解决方案


当您不在现场时,您可以使用简单的 if 语句禁用它:

 public float speed = 12f;
 public float gravity = -9.81f;
 public CharacterController controller;
 public float jumpHeight = 3f;

 public Transform groundCheck;
 public float groundDistance = 0.4f;
 public LayerMask groundMask;

 bool isGrounded;

 // Update is called once per frame
 void Update()
 {
      isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

     if(isGrounded && velocity.y < 0)
     {
          velocity.y = -2f;
     }

     float x = Input.GetAxis("Horizontal");
     float z = Input.GetAxis("Vertical");
     Vector3 move = transform.right * x + transform.forward * z;
     if (!isGrounded)
     {
         controller.Move(move * speed * Time.deltaTime);
     }
     if(Input.GetButtonDown("Jump") && isGrounded)
     {
         velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
     }

      velocity.y += gravity * Time.deltaTime;

      controller.Move(velocity * Time.deltaTime);
 }
 }

我所做的是向 controller.Move() 函数添加一个 if 语句。这是没有其余代码的样子:

if (isGrounded)
{
    controller.Move(move * speed * Time.deltaTime);
}

这是我写的。if 语句说:如果角色在地上,则移动它。这意味着它将在空中停止更新角色的位置。

如果您想要更逼真的物理效果,请将其添加到您的脚本中:

if (isGrounded)
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 move = transform.right * x + transform.forward * z;
    controller.Move(move * speed * Time.deltaTime);
}
else
{
    velocity.x = Mathf.Sqrt(move.x * var2);
    velocity.z = Mathf.Sqrt(move.z * var2);
}

我复制了您的跳转脚本,并对其稍作更改以复制您可能想要的物理效果。更改 var1 和 var2 的名称。Var 2 是您在空中时施加的力的大小,只需尝试您想要的。


推荐阅读