unityで、簡単なシューティングゲームを2Dを作ってみたいと思います。
オブジェクトの設定

コード
▼PlayerScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
//3)弾のプレハブを定義
public GameObject bulletPrefab;
// Update is called once per frame
void Update()
{
// 1)入力を取得(←→キー、↑↓キー)
float moveX = Input.GetAxis("Horizontal"); // 左右
float moveY = Input.GetAxis("Vertical"); // 上下
//2)移動実行
//transform.position(座標) = 絶対移動(場所指定)←やり方によってはワープに近い
//transform.Translate(Vector3 移動量) は「現在の位置からの相対移動」
transform.Translate(new Vector3(moveX, moveY, 0f) *10f * Time.deltaTime);
//4)スペースキーで弾生成
if (Input.GetKeyDown(KeyCode.Space))
{
//Instantiate(何を, 位置, 回転);
//「回転を表す値(Quaternion)クオータニオン」の 初期状態(=回転していない状態)
Instantiate(bulletPrefab, transform.position + Vector3.up * 0.5f, Quaternion.identity);
}
}
//5)敵に当たったらプレイヤー破壊
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "EnemyTag")
{
Destroy(gameObject); //自分自身を消す
Time.timeScale = 0f; //ゲームを止める
Camera.main.backgroundColor = Color.red;// 背景色を赤に変更
}
}
}
▼BulletScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
// Update is called once per frame
void Update()
{
//1)弾が上に動いていく
transform.Translate(Vector3.up *10f * Time.deltaTime);
// 2)画面外で削除
if(transform.position.y > 7f)
{
Destroy(gameObject);
}
}
//3)当たったら(例:OnCollisionEnter2D)
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "EnemyTag")
{
Destroy(collision.gameObject); //当たった相手
Destroy(gameObject); //自分自身
}
}
}
▼EnemyScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
// Update is called once per frame
void Update()
{
//1)下に落下してくる
transform.Translate(Vector3.down * 2f *Time.deltaTime);
//2)下まで行ったら削除
if(transform.position.y < -6f)
{
Destroy(gameObject);
}
}
}
▼GameManager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
//1)敵のプレハブを定義
public GameObject enemyPrefab;
// Start is called before the first frame update
void Start()
{
//3)InvokeRepeating("実行する関数名", 開始時間, 間隔);
InvokeRepeating("CreateEnemy", 1f, 3f);
}
//2)敵出現の関数
void CreateEnemy()
{
float enemyX = Random.Range(-12f,12f);
Vector3 enemyPos = new Vector3(enemyX, 6f,0); //敵を生成する座標
//Instantiate(何を, 位置, 回転);
Instantiate(enemyPrefab, enemyPos, Quaternion.identity);
}
}