LoginSignup
11
11

More than 5 years have passed since last update.

Unity2D ~キャラクター操作ジャンプ編~

Posted at

ジャンプスクリプト

前回のキャラクター操作スクリプト作成の引き続きっぽいやつ

とりあえずスペース押したらジャンプ

public float flap = 1000f;

void Update () {
        if (Input.GetKeyDown("space"))
        {
            rb2d.AddForce(Vector2.up * flap);
        }
}

これを追加すればスペースを押したらジャンプ
 →このコードだと何段階でもジャンプできちゃいます
飛ぶ量を変えたいときはflap変更
速さを変えたいときはInspentorタブのRigidbody2DのGravityScaleの数値を上げればok
gfsrdgsg.PNG

1段ジャンプ制限

bool jump = false;

    void Update () {
        if (Input.GetKeyDown("space") && !jump)
        {
            rb2d.AddForce(Vector2.up * flap);
            jump = true
        }
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        jump = false;
    }

OnCollisionEnter2Dはオブジェクトに衝突した時に呼び出される
2Dの場合は2Dまでの名前指定が必要です
注:衝突するオブジェクトにはどちらもcolliderとrigidbodyが付いている必要があります
地面には物理法則はいらないので、Bodytypeをstaticにでもしておきましょう。

地面にぶつかったときのみジャンプ

オブジェクトそれぞれにタグを付けることで、衝突時の判定に使えます
地面のオブジェクトのInspertorのTagをGroundに変更

gfdsgraegergs.PNG

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            jump = false;
        }
    }

こんな感じ

まとめ

大体こんな感じで横スクロールアクションの超基本は出来たかな


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

public class Player : MonoBehaviour {

    //変数定義
    public float flap = 1000f;
    public float scroll = 5f;
    float direction = 0f;
    Rigidbody2D rb2d;
    bool jump = false;

    // Use this for initialization
    void Start () {
        //コンポーネント読み込み
        rb2d = GetComponent<Rigidbody2D>();
    }


    // Update is called once per frame
    void Update () {

        //キーボード操作
        if (Input.GetKey(KeyCode.RightArrow))
        {
            direction = 1f;
        }else if (Input.GetKey(KeyCode.LeftArrow))
        {
            direction = -1f;
        }else
        {
            direction = 0f;
        }


        //キャラのy軸のdirection方向にscrollの力をかける
        rb2d.velocity = new Vector2(scroll * direction, rb2d.velocity.y);

        //ジャンプ判定
        if (Input.GetKeyDown("space") && !jump)
        {
            rb2d.AddForce(Vector2.up * flap);
            jump = true;
        }


    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.CompareTag("Ground"))
        {
            jump = false;
        }
    }
}

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11