
unityで、簡単な横スクロール型のアクションゲームを作ってみたいと思います。
右の方から上下の壁がやってきて、 スペースキーを押したら、プレイヤーがジャンプできるようになっています。 で、上手いこと、隙間を潜り抜けるとゲームは続行しますが 壁にぶつかってしまうと、こうですね。 自身が赤くなって、ゲームが留まってゲームオーバー という簡単な2Dゲームです。
【目次】
01:10 [1]オブジェクトの配置(プレイヤー、壁)
08:50 [2]プレハブ化(壁セット)
09:55 [3]スペースキーでジャンプ
16:45 [4]壁の移動
22:00 [5]壁を定期的に出す
31:10 [6]当たったら
コード
▼PlayerScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
//1)Rigidbodyが扱える変数を用意
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
//2)Rigidbodyを取得して代入
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//3)スペースキーを押したらジャンプ
if (Input.GetKeyDown(KeyCode.Space))
{
//rb.velocity = new Vector2(0, 5f);
rb.velocity = Vector2.up * 5f;
}
}
//4)当たったら
private void OnCollisionEnter2D(Collision2D collision)
{
Time.timeScale = 0;// ゲームを止める
GetComponent<SpriteRenderer>().color = Color.red;
}
}
▼WallScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallScript : MonoBehaviour
{
// Update is called once per frame
void Update()
{
//1)左に移動
transform.position += Vector3.left * 2f * Time.deltaTime;
//2)画面から出たら削除
if(transform.position.x < -10f)
{
Destroy(gameObject);
}
}
}
▼GameManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
//1)壁のプレハブ変数を定義
public GameObject wallPrefab;
// Start is called before the first frame update
void Start()
{
//3)InvokeRepeating("実行する関数名", 開始時間, 間隔);
InvokeRepeating("CreateWall", 1f, 2f);
}
//2)壁生成の関数
void CreateWall()
{
// 位置を決める
float randomY = Random.Range(-3f ,3f);
Vector3 wallPos = new Vector3(5f, randomY, 0f);
//ランダムな高さで壁生成
//Instantiate(何を, 位置, 回転);
Instantiate(wallPrefab, wallPos, Quaternion.identity);
}
}
ざっくり下書き
1)プレイヤーを作る(鳥)
Hierarchyで 右クリック → 2D Object → Sprite → Circle を作る(仮の鳥)
Player(Circle)
Rigidbody2D を追加
Gravity Scale:1(自然に落ちる)
CircleCollider2D を追加(当たり判定)
2)ジャンプ処理を作る(PlayerScript)
3)Wall(障害物)の作成
●2D Object → Sprite → Square で細長いパイプ上の四角を作る(上下で1組)
●名前を PipeTop と PipeBottom にする
●BoxCollider2D を追加
●空のオブジェクト PipeSet を作って、上下のパイプを子にする(position10)
●PipeSet に PipeScript というスクリプトをアタッチ
4)パイプを定期的に出す
●パイプセットをプレハブ化
●からのオブジェクトGameManagerを作る
●スクリプトGameManagerを作る
5)ゲームオーバー処理(当たり判定)
●プレイヤースクリプト