我遵循了Brackey的Unity第一人称控制器教程,但无法跳跃。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementScript : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
[Header("Keybinds")]
public KeyCode jumpKey = KeyCode.Space;
public float JumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, 1 + 0.3f, 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.GetKeyDown(jumpKey) && isGrounded)
{
velocity.y = Mathf.Sqrt(JumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
我发现如果我从if语句中删除isGrounded,那么我可以跳,但是无限跳;如果isGrounded在代码中,那么我根本不能跳。
我试着从if语句中删除isGrounded,这给了我跳跃的能力,但是我可以永远跳跃而不接触地面。
我尝试删除行velocity.y += gravity * Time.deltaTime;
,但无法跳转到那里。
我试着删除isGrounded,所有对它的引用,以及涉及地面的东西,这些导致跳一次,然后继续浮起来。
我尝试将isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
更改为Physics.Raycast(transform.position, Vector3.down, 1 + 0.3f, groundMask);
,但没有任何更改。
我仔细检查了地面层已经应用到地面,地面检查已经链接和掩模选择。
我完全被难住了,为什么这是不工作。任何和所有的帮助将非常感谢,谢谢!
2条答案
按热度按时间rm5edbpk1#
您需要在检查器中指定接地掩码!!!you need to assign everythingmy player is doing fine after applying the ground mask
nwlqm0z12#
检查您的地面是否具有在检查器中选择的地面标签/图层