Unity 3D 运动具有这种内置功能,当您按住按键停止时,它会滑动。如何删除此幻灯片?
公平警告,我还没有尝试过任何东西。我对 Unity 很陌生,认为它很可能只是我需要单击的某个按钮,因此请提供帮助。
这是我正在使用的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
float moveSpeed;
float walkSpeed = 3;
float sprintSpeed = 6;
public CharacterController controller;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 8.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
moveSpeed = sprintSpeed;
}
else
{
moveSpeed = walkSpeed;
}
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 * moveSpeed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
最佳答案
我非常乐意回答你的问题,但我不能忽略这个花絮。我怎么强调都不为过。如果您是 Unity 新手,您应该尽可能避免发布此类问题。我并不是阻止您提出问题,但由于您是新人,因此在发布任何内容之前请先尝试一下。通过删除变量和代码行来自行找出解决方案,而不是立即得到答案,您将学到更多东西。
无论如何,我相信答案就在代码的最后两行中:
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
让我们逐行思考这个问题。剖析每一行并尝试真正理解它们的含义。当您运行代码时,您将收到来自用户的三个主要输入:
if (Input.GetKey(KeyCode.LeftShift))
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
if (Input.GetKey(KeyCode.LeftShift))
只是检查您的用户是否想要运行。另外两个正在接收可能是鼠标移动的输入。这些主要用于定义用户的移动。我们知道这一点是因为它们直接与接下来的两行相关:
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * moveSpeed * Time.deltaTime);
现在,当您仔细观察时,它告诉我们,如果用户没有移动鼠标,则 Vector3 move
将为 0。这意味着我们的玩家将停止移动,并且在那里应该没有理由他们滑行。 但是,请看一下接下来的两个。
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
这些不一定是由用户输入驱动的。这意味着考虑到它们与您的 Controller
相关联,并且其他移动调用在没有用户输入的情况下不会运行,这两行一定是导致滑行问题的罪魁祸首。
所以删除这些,你应该会很好。但是,我必须澄清,提出问题很好,但是打破代码以了解更多信息会更好。作为一个挑战,我认为你应该研究一下是什么驱动了 velocity.y
...或者也许 isGrounded
...这将告诉你更多关于为什么会发生滑行!
希望这有帮助!
关于unity-game-engine - 如何消除 3D 统一运动中的滑动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61768673/