norablog-techのブログ

このブログは、自分の忘備録的にアウトプットするためのブログとなっております。

【Unity】PreFab機能を使って弾を撃つ

変更:
2022/01/25 変数名を"アッパーキャメル"から、すべて小文字に修正。

 

今回はUnityのPreFab機能を使って、弾を生成し、スペースキーを叩く度に発射するプログラムを作成します。

Unityのプレハブ機能とObject.Instantiate関数を使います。

 


www.youtube.com

 

上記の動画にあるように、”Bullet”をプロジェクトに追加、プレハブ化して下記のスクリプトを”追加・作成”します。

BulletPreFabController.cs (cord)

 

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

public class BulletPreFabController : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //BulletPreFabの位置を1Sec毎に1fだけ+Y方向(上)に動かす
        transform.position += new Vector3(
                0f,
                1f * Time.deltaTime,
                0f
            );
    }
}

 

※移動の部分は敵機の動きと帆も同じ。向きとスピードを変えているだけです。

 

次にプレーヤー機(Diamond)のスクリプトに、”スペースキーを叩く度に弾を発射する”記述を追記します。

 

DiamondController.cs

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

public class DiamondController : MonoBehaviour
{

 //追加
    //GameObjectの宣言
    //Unityで使うオブジェクトは"GameObject"クラスになります。
    //public宣言すると、GUIエディターに"Diamond"のインスペクターに"BulletPreFab"の項目ができます。(動画を参照)

    public GameObject bulletprefab;  //修正

 

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float dx = Input.GetAxis("Horizontal") * Time.deltaTime * 4f;
        float dy = Input.GetAxis("Vertical") * Time.deltaTime * 4f;

        transform.position = new Vector3(
                Mathf.Clamp(transform.position.x + dx, -8.5f, 8.5f),
                Mathf.Clamp(transform.position.y + dy, -4.5f, 4.5f),
                0f
            );

  //追加
   //Spaceキーを叩くたびに"Shoot()"関数を呼び出す。
   //キーの指定を変えれば、Spaceキーでなくてもよい。
        if (Input.GetKeyDown(KeyCode.Space))

        {
            Shoot();
        }
    }

    //追加
    //弾を撃つ関数

    private void Shoot()
    {
        //Diamond(Player機)の中心位置から撃つ
        Instantiate(bulletprefab, transform.position, transform.rotation);  //修正
    }
}

 

UnityのGUIエディター上で、"BulletPreFab"をインスペクターの欄にドラッグ&ドロップで追加、スクリプトをアタッチします。

さらにプレイヤー機のスクリプトにスペースキーを叩く度、弾を発射する機能を追加します。

 

動画の解説と併せて見てください。

 

ではでは。