我为一个基本的 (FPS) 播放器控制器编写了这个脚本,但是在跳跃时它不起作用。它有效,但它非常小故障。这是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FirstPersonController : MonoBehaviour
{
public CharacterController controller;
public Transform groundCheck;
public LayerMask groundMask;
public int Speed;
public float SprintMultipliyer = 2f;
public float gravity = -9.81f;
public float JumpHeight;
public float groundDistance = 0.4f;
private float a = 1f;
private float SprintSpeed = 1;
private float HorizontalInput;
private float ForwardInput;
bool IsonGround;
Vector3 velocity;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
IsonGround = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
//this checks if the player is on the ground and his vertical [y] is less then 0 (wich is good for a one height and not good for multiple diffrent heigths)
if (IsonGround)
{
velocity.y = -3f;
}
//this if statement ischecking if the player presses [spacebar] and if he is on the ground
if (Input.GetButtonDown("Jump") && IsonGround)
{
//the math for a jump is: the square root of the height you want to jump times [*] -2 * gravity or in the programm: Mathf.Sqrt(JumpHeight * -2f * gravity);
velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
}
if (Input.GetButton("Sprint") && IsonGround)
{
SprintSpeed = a * SprintMultipliyer;
}
else
{
SprintSpeed = 1;
}
//Input.GetAxis("[name of the axis]") is used to set the variables to 1 when the player presses [A/D] or [W/S]
HorizontalInput = Input.GetAxis("Horizontal");
ForwardInput = Input.GetAxis("Vertical");
//this works by = transform is multiplied with HorizontalInput [A/D] and then multipliyng transform.forward with ForwardInput [W/S]
Vector3 move = transform.right * HorizontalInput + transform.forward * ForwardInput;
//controller is a public CharacterControler that is called [controller]
//.Move is a function similar to transform.Translate
//move is a Vector3 that is used for left/right and forward/backward input
controller.Move(move * Speed * SprintSpeed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
我尝试改变重力、跳跃高度和地面距离,但仍然无法正常工作。地面距离物体也在地面上并且地面在地面层上。