[英]I'm trying to get my cube to only jump on the ground but my if statement isn't working
public Rigidbody rb;
public bool cubeIsOnTheGround = true;
public float speed = 10;
Vector3 direction;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
direction = input.normalized;
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
}
if (cubeIsOnTheGround == true)
{
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
cubeIsOnTheGround = false;
}
}
}
void FixedUpdate()
{
rb.position += direction * speed * Time.deltaTime;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
cubeIsOnTheGround = true;
}
}
if 语句 boolIsOnTheGround 不工作。 我想做的是检查立方体是否在地面上,这样我就知道你什么时候可以跳了。 立方体只是通过按空间无限反弹。
在您的代码中,您有两个 if 块:
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
}
if (cubeIsOnTheGround == true)
{
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
cubeIsOnTheGround = false;
}
}
第一个 if 块不检查cubeIsOnTheGround
,所以只要按下跳转按钮它就会跳转。 如果您删除第一个块,此行为应该停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.