玩家的跳跃极限

时间:2019-05-03 12:16:40

标签: unity3d

我的播放器连续跳跃,我想使其仅跳跃2次而不会触地(如果他触地,他会死)。我如何限制它?我应该再制作一个脚本吗?这是播放器脚本。我还想让他从箱子对撞机跌落到另一个箱子对撞机时不要旋转。我的游戏是2D游戏。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float moveSpeed = 300;
    public GameObject character;
    private Rigidbody2D characterBody;
    private float ScreenWidth;
    private Rigidbody2D rb2d;
    private Score gm;
    public bool isDead = false;
    public Vector2 jumpHeight;

    void Start()
    {
        ScreenWidth = Screen.width;
        characterBody = character.GetComponent<Rigidbody2D>();
        gm = GameObject.FindGameObjectWithTag("gameMaster").GetComponent<Score>();
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isDead) { return; }
        if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
        {
            GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
        }

        int i = 0;
        while (i < Input.touchCount)
        {
            if (Input.GetTouch(i).position.x > ScreenWidth / 2)
            {
                RunCharacter(1.0f);
            }

            if (Input.GetTouch(i).position.x < ScreenWidth / 2)
            {
                RunCharacter(-1.0f);
            }

            ++i;
        }
    }    

    void FixedUpdate()
    {
#if UNITY_EDITOR
        RunCharacter(Input.GetAxis("Horizontal"));
#endif 
    }

    private void RunCharacter(float horizontalInput)
    {
        characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("ground")) // this will return true if the collision gameobject has ground tag on it.
        {
            isDead = true;
            rb2d.velocity = Vector2.zero;
            GameController.Instance.Die();
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.CompareTag("coin"))
        {
            Destroy(col.gameObject);
            gm.score += 1;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

只需添加一个计数器,例如

private int jumpCount = 0;

...

    if (jumpCount < 2 && (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space)))
    {
        // You already have that reference from Start
        // should avoid to use GetComponent again
        rb2d.AddForce(jumpHeight, ForceMode2D.Impulse);
        jumpCount++;
    }

并在允许玩家再次跳跃时重置它

jumpCount = 0;

例如在

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("ground")) // this will return true if the collision gameobject has ground tag on it.
    {
        isDead = true;
        rb2d.velocity = Vector2.zero;
        GameController.Instance.Die();
    }

    jumpCount = 0;
}