Unity5: 2D平台游戏:跳跃到不同的高度

本文关键字:高度 跳跃 2D 平台 游戏 Unity5 | 更新日期: 2023-09-27 18:15:16

我正在尝试在c#中实现字符跳转但是我想让他跳到不同的高度,这取决于你保持跳跃按钮的时间。
例如,如果你瞬间击中空间,你就不会跳得那么高相反,角色会跳得更高,但高度有限。
下面是我的代码:

private Rigidbody2D rb;
private Transform lowerPoint;
private new SpriteRenderer renderer;
private Animator anim;
private Transform spawPosition;
[SerializeField]
float speed = 3f;
[SerializeField]
float jumpForce = 3f;
[SerializeField]
Image backgroundImage;
[SerializeField]
LayeredSpikes script;
float secondJumpForce;
[SerializeField]
float additionalVelocity;
const float ADDITION_VELOCITY_LIMIT = 0.9f;
bool isGrounded;
bool isAlive;
bool hasSecondJump;
void Awake()
{
    rb = GetComponent<Rigidbody2D> ();
    renderer = GetComponent<SpriteRenderer> ();
    lowerPoint = GetComponentInChildren<Transform> ();
    anim = GetComponent<Animator> ();
    spawPosition = GameObject.FindGameObjectsWithTag ("Respawn")[0].GetComponent<Transform> ();
}
void Start()
{
    ResetVelocity ();
    isGrounded = false;
    isAlive = true;
    hasSecondJump = true;
    Spawn ();
    secondJumpForce = jumpForce * 0.75f;
}
void Update()
{
    if (isAlive) 
    {
        if (isGrounded) 
        {
            AnimState = AnimationState.Idle;
            hasSecondJump = true;
            additionalVelocity = 0f;
        }
        if (Input.GetButtonDown ("Jump")) 
        {
            Jump ();
        }
        if (Input.GetButton ("Jump")
            && additionalVelocity <= ADDITION_VELOCITY_LIMIT) 
        {
            additionalVelocity += ADDITION_VELOCITY_LIMIT / 3;
            rb.AddForce( Vector2.up * additionalVelocity );
        }
        if (Input.GetButton ("Horizontal")) 
        {
            Run ();
        }
    }
}
private void Jump()
{
    AnimState = AnimationState.Jump;
    float force;
    if (isGrounded) 
    {
        force = jumpForce;
    } 
    else 
    {
        if (hasSecondJump) 
        {
            ResetVelocity ();
            force = secondJumpForce;
            hasSecondJump = false;
        } 
        else 
        {
            force = 0f;
        }
    }
    rb.AddForce (Vector2.up * force, ForceMode2D.Impulse);
    if (force != 0f) 
    {
        //script.Trigger ();
    }
}
void ResetVelocity()
{
    rb.velocity = Vector2.zero;
    additionalVelocity = 0f;
}

我试着在跳跃的中间增加力量,但没有结果。

Unity5: 2D平台游戏:跳跃到不同的高度

乍一看,我可以观察到bool变量isGrounded总是false。这个问题很棘手,因为这是你的第二次跳跃,但不是你的第一次跳跃,这就是为什么你很难发现它!

设置变量isGrounded = true作为Start()的默认值,然后当您进行第一次跳跃时,设置isGrounded = false

然后你可以使用Colliders来检测你的角色何时回到地面,如果是这样,你需要使你的isGrounded变量public isGrounded

希望我能帮到你!

  • 一个