簡體   English   中英

Unity 2D 為什么我的角色在地面不平坦時不會跳躍?

[英]Unity 2D Why doesn't my character jump when the ground isn't flat?

我的角色在平面上彈跳,如圖所示。 但是當地板彎曲時它不會跳。我不知道我做錯了什么。 我的角色在平地上跳躍。 但是當地面不平坦時,我的角色不會跳躍。

在此處輸入圖片說明

我的跳轉腳本在這里:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class WalkJumpFire : MonoBehaviour {

    public CharacterController2D kontroller;
    Rigidbody2D rb;
    float dirX;

    [SerializeField]
    float moveSpeed = 5f, jumpForce = 800f, bulletSpeed = 500f;

    bool facingRight = true;
    Vector3 localScale;

    public Transform barrel;
    public Rigidbody2D bullet;

    // Use this for initialization
    void Start () {
        localScale = transform.localScale;
        rb = GetComponent<Rigidbody2D> ();
    }

    // Update is called once per frame
    void Update () {
        dirX = CrossPlatformInputManager.GetAxis ("Horizontal");

        if (CrossPlatformInputManager.GetButtonDown ("Jump"))
            Jump ();

        if (CrossPlatformInputManager.GetButtonDown ("Fire1"))
            Fire ();
    }

    void FixedUpdate()
    {
        rb.velocity = new Vector2 (dirX * moveSpeed, rb.velocity.y);

    }

    void LateUpdate()
    {
        CheckWhereToFace ();
    }

    void CheckWhereToFace()
    {
        if (dirX > 0)
            facingRight = true;
        else
            if (dirX < 0)
                facingRight = false;
        if (((facingRight) && (localScale.x < 0)) || ((!facingRight) && (localScale.x > 0)))
            localScale.x *= -1;
        transform.localScale = localScale;
    }

    void Jump()
    {
        if (rb.velocity.y == 0)
            rb.AddForce (Vector2.up * jumpForce);
    }

    void Fire()
    {
        var firedBullet = Instantiate (bullet, barrel.position, barrel.rotation);
        firedBullet.AddForce (barrel.up * bulletSpeed);
    }
}

正如@derHugo 提到的,使用剛體躺在地上的條件(通過 isGrounded 方法)來激發你的跳躍:

public bool isGrounded;  

//During collisions you would still want your object to jump, such as jumping while touching the corner of a wall, so:
void OnCollisionStay()
{
        isGrounded = true;
}  

//Your not able to jump right after collision: (Also add layers so your object can't pass through walls or entities in the game)
void OnCollisionExit()
{
        isGrounded = false;
}

//Jump only if your object is on ground:
void Jump()
{
       if(isGrounded)
       {
          rb.AddForce (Vector2.up * jumpForce);
          //set it to false again so you can't multi jump:
          isGrounded = false;
       }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM