LoginSignup
3
3

More than 5 years have passed since last update.

歩く・ジャンプする アクションゲーの基礎的処理【Unity2D】

Posted at

アクションゲームの基礎

毎回過去プロジェクトを開くのが面倒なのでメモ。いろいろなところから引っ張ってきてる&ベストな書き方かわからんので自分用ということで……

ジャンプとか移動とか

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

public class Player : MonoBehaviour {

    Rigidbody2D rb;

    bool leftBool;
    bool rightBool;

    [SerializeField] float playerSpeed;
    [SerializeField] float playerFlap;

    public const int MAX_JUMP_COUNT = 1;    // ジャンプできる回数。
    int jumpCount = 0;
    bool isJump = false;


    void Start () {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update() {
        leftBool = Input.GetKey(KeyCode.A);
        rightBool = Input.GetKey(KeyCode.D);
        if (jumpCount < MAX_JUMP_COUNT && Input.GetKey(KeyCode.Space)) isJump = true;
    }

    void FixedUpdate() {
        if (leftBool) transform.position += new Vector3(-playerSpeed, 0,0);
        if (rightBool)  transform.position += new Vector3(playerSpeed, 0,0);

        if (isJump) {
            // 速度をクリアして2回目のジャンプも1回目と同じ挙動にする。 
            rb.velocity = Vector3.zero;

            // ジャンプさせる。 
            rb.AddForce(Vector3.up * flap);
           // audioSource.PlayOneShot(jumpOto);

            // ジャンプ回数をカウント。 
            jumpCount++;

            // ジャンプを許可する。 
            isJump = false;
        }
    }

    void OnCollisionEnter2D(Collision2D other) {
        if (other.gameObject.tag == "Ground") {
            jumpCount = 0;
        }
    }
}

地面にはGroundのタグを付ける。

(逐次追記していきます)

3
3
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
3
3