【发布时间】:2021-04-19 08:33:56
【问题描述】:
我对 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);
}}
【问题讨论】:
-
您已经知道您的播放器是否
isGrounded,因此当播放器未接地时,您可以忽略播放器输入,因此在输入之前执行 if(isGrounded){return;} 之类的操作。与此相关的一个问题是,您似乎在计算自己的重力?即使刚体重力应该已经影响您的对象,除非您关闭组件上的重力。