我对unity很陌生,想创建一个fps运动.我从Brackeys找到了这个教程,它的效果比较好,但如果你跳的时候头上有天花板,你就会飞一会儿。我很抱歉问这样一个基本的问题,但我找不到任何东西。这里有一些代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
Animator animator;
public float speed = 7f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
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");
if (x != 0)
{
animator.SetBool("WalkXTrigger", true);
x /= 2;
}
else
{
animator.SetBool("WalkXTrigger", false);
}
if (z != 0)
{
if (z<0)
{
animator.SetBool("WalkBackTrigger", true);
z /= 1.5f;
}
if (z>0)
{
animator.SetBool("WalkTrigger", true);
}
}
else
{
animator.SetBool("WalkTrigger", false);
animator.SetBool("WalkBackTrigger", false);
}
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
animator.SetBool("JumpTrigger", true);
}
else
{
animator.SetBool("JumpTrigger", false);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
所以我认为有2个选择:1.当角色撞到天花板时,将其向下移动2.测量角色和天花板之间的空间,并将其设置为等于跳跃高度我的问题:我不知道如何做这些希望我的英语没问题,问题描述得足够好谢谢你的帮助。
我不是100%确定你的角色是否一直在飞,或者只是停留在那里一两秒钟,但无论哪种方式,这一点代码将工作。
public GameObject ceiling; //set this to your ceiling in the editor.
public float ceilingDown = 0.5; //if this value doesn't work, just mess around with it a little.
void OnTriggerEnter(ceiling){
velocity.y -= ceilingDown;
}
如果你把这个加到你的代码里,它应该会迫使玩家稍微向下。在这之后,重力会接管。
你在更新循环的最后有这个,所以我假设你的角色一直在飞?
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
继续编码和练习,你会明白的!