我正在使用角色和物理学制作简单的游戏。角色使用胶囊对撞机。我设法通过增加力量来使角色移动,对其进行限制,以使它们不会达到巨大的价值,并且在没有按下任何运动键(w a s和d)时增加相反的作用力,从而使角色停止得更快。最后添加了一些动画。问题是我在场景中添加了地形并为其增加了一些高度。每当我到达顶部并按住“ w”前进时,我的角色就会失去与旋转木马的接触,并开始基本飞行,尽管它缓慢开始下降(速度太慢)。当我停止按“ w”时,重力再次开始起作用,物体开始以正常速度掉落。有人可以帮忙吗?
public class PlayerController : MonoBehaviour {
public Animator anim;
public Rigidbody rb;
public float speed;
public float rotationSpeed;
public float maxSpeed;
public float maxRotationSpeed;
void Start () {
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
}
void Update () {
//Manage animations
if (Input.GetKey("w"))
{
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
void FixedUpdate()
{
//Get input
float moveHorizontal = Input.GetAxis("Horizontal") * Time.deltaTime;
float moveVertical = Input.GetAxis("Vertical") * Time.deltaTime;
//Add forces to object
rb.AddRelativeForce(new Vector3 (0.0f, 0.0f, moveVertical) * speed);
rb.AddTorque(transform.up * moveHorizontal * rotationSpeed);
//Limit velocity and rotation
if (Vector3.Magnitude(rb.velocity) > maxSpeed)
{
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
}
if (rb.angularVelocity.magnitude > maxRotationSpeed)
{
rb.angularVelocity = Vector3.ClampMagnitude(rb.angularVelocity, maxRotationSpeed);
}
//Stop object if no movement key is being pressed
if (!Input.GetKey("w") && rb.velocity.magnitude > 0.0001 && Vector3.Dot(rb.transform.forward,rb.velocity.normalized) > 0)
{
rb.velocity = Vector3.zero;
}
if (!Input.GetKey("s") && rb.velocity.magnitude > 0.0001 && Vector3.Dot(rb.transform.forward, rb.velocity.normalized) < 0)
{
rb.velocity = Vector3.zero;
}
if ((!Input.GetKey("a") || !Input.GetKey("s")) && rb.angularVelocity.magnitude > 0.0001)
{
rb.angularVelocity = Vector3.zero;
}
Debug.Log(rb.transform.position.y);
}
}