[英]Unity/C# Weird glitch in FPS controller
i have a weird glitch, when i walk down from a corner (i dont press jump), the player will falling down with very fast speed. 我有一个奇怪的故障,当我从一个角落走下来时(我不按跳键),玩家将以非常快的速度摔倒。 If i jump, then everything goes normal.
如果我跳,那么一切都会正常。 (Its Quill18 FPS controller, i learn from there so thats why i dont use the built in controller instead)
(它的Quill18 FPS控制器,我从那里学习,所以这就是为什么我不使用内置控制器的原因)
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(CharacterController))]
public class FirstPersonController : MonoBehaviour
{
public float movementSpeed = 5.0f;
public float mouseSensitivity = 5.0f;
public float jumpSpeed = 20.0f;
float verticalRotation = 0;
public float upDownRange = 60.0f;
float verticalVelocity = 0;
CharacterController characterController;
// Use this for initialization
void Start()
{
// Screen.lockCursor = true;
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
// Rotation
float rotLeftRight = Input.GetAxis("Mouse X") * mouseSensitivity;
transform.Rotate(0, rotLeftRight, 0);
verticalRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation = Mathf.Clamp(verticalRotation, -upDownRange, upDownRange);
Camera.main.transform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
// Movement
float forwardSpeed = Input.GetAxis("Vertical") * movementSpeed;
float sideSpeed = Input.GetAxis("Horizontal") * movementSpeed;
verticalVelocity += Physics.gravity.y * Time.deltaTime;
if (characterController.isGrounded && Input.GetButton("Jump"))
{
verticalVelocity = jumpSpeed;
}
Vector3 speed = new Vector3(sideSpeed, verticalVelocity, forwardSpeed ;
speed = transform.rotation * speed;
characterController.Move(speed * Time.deltaTime);
}
}
The problem is that every frame you're running this line: 问题是您正在运行此行的每一帧:
verticalVelocity += Physics.gravity.y * Time.deltaTime;
verticalVelocity + = Physics.gravity.y * Time.deltaTime;
Thus, you're gaining "momentum" each second, and it wont stop ever until you jump because you're "resetting" the Y velocity to a normal value. 因此,您每秒都在获得“动量”,并且直到您跳动它都不会停止,因为您是将Y速度“重置”为正常值。 I've ran into this problem before, and it can be fixed simply by only adding the Y velocity when you're not grounded.
我以前曾遇到过这个问题,只需在不接地时仅添加Y速度即可解决此问题。 You can use Raycast to check if you have ground, and if you dont, increase
verticalVelocity
by that amount. 您可以使用Raycast来检查是否有地面,如果没有地面,则可以将
verticalVelocity
增加该数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.