我为一个基本的(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 (which is good for a one height and not good for multiple different heights)
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 program: 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);
}
}
我尝试改变重力,跳跃高度和地面距离,但仍然不能正确工作。地面距离对象也在地面上,地面在地面层上。
1条答案
按热度按时间b91juud31#
我将groundcheck对象放在地面图层上,并将地面距离设置为0.1,工作正常,没有故障