【发布时间】:2022-01-22 07:08:35
【问题描述】:
我试图让我的角色能够在 2D Unity 项目中在空中/双跳时跳跃一次,下面是我的代码。玩家角色在空中可以跳一次但不能再跳一次,虽然我认为它在程序的眼中实际上是有效的,因为 jumpCounter 变量有时确实会增加到 1,但主要是直接增加到 2,所以我认为这是要做的事情即使我只按下一次空格键,也会在一帧中多次按下空格键?
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
float xMovement = 0;
float jumpValue = 0;
Vector2 targetVelocity = new Vector2(0, 0);
Rigidbody2D myRigidBody;
public bool isGrounded = true;
public int jumpCounter = 0;
// Start is called before the first frame update
void Start()
{
myRigidBody = GetComponent<Rigidbody2D>();
myRigidBody.gravityScale = 8;
//myRigidBody.simulated = false;
}
// Update is called once per frame
void Update()
{
}
void checkInputs()
{
xMovement = Input.GetAxis("Horizontal");
jumpValue = 0;
if (isGrounded)
{
jumpValue = Input.GetAxis("Jump");
if (jumpValue > 0)
{
jumpCounter += 1;
}
if (jumpCounter >= 2)
isGrounded = false;
}
}
private void FixedUpdate()
{
checkInputs();
myRigidBody.velocity = new Vector2(xMovement * 20, myRigidBody.velocity.y);
myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, jumpValue * 20);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.CompareTag("Ground"))
{
isGrounded = true;
jumpCounter = 0;
}
}
}
【问题讨论】:
-
你为什么用
GetAxis跳转?