使用Vector3.让玩家跳一次以上



嗨,我是新的c#,我刚刚做了一个代码,让玩家跳,它工作得很好,但问题是,如果我点击空格按钮两次,它会做一个双跳,如果我继续做它会飞....我只想要一次跳跃,如果玩家碰到地面可以再次跳跃,而不是两次跳跃……我所尝试的是改变与vector3相乘的数字。Up to just jump and make a

public float jump = 5f;

也没有工作的任何方式这是我的源代码希望你理解的问题和帮助我

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
public float speed1;
public float jump = 5f;

// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed1);
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space))
{
GetComponent<Rigidbody>().AddForce(Vector3.up * jump, ForceMode.VelocityChange);
}
}
}

您可以创建一个标志wasGrounded,在跳转后将其设置为false。玩家只能跳,当wasGrounded == true。你还在地面上添加了一个碰撞器。一旦玩家触地,你重置wasGrounded标志为真。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
public float speed = 5f;
public float speed1;
public float jump = 5f;
private bool wasGrounded = true;

// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.forward * speed1);
if (Input.GetKeyDown(KeyCode.A))
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
if (Input.GetKeyDown(KeyCode.Space) && wasGrounded)
{
wasGrounded = false;
GetComponent<Rigidbody>().AddForce(Vector3.up * jump, ForceMode.VelocityChange);
}
}
void OnCollisionEnter(Collision other)
{
// Change to string you compare it to to the tag of your ground gameobject.
if (other.gameObject.tag == "Ground")
{
wasGrounded = true;
}
}
}

确保有" itrigger& quot;在地面碰撞器上设置false

最新更新