MENU

スペースを押している間だけいい感じの間隔で弾が発射できる

概要

 unityで作る2dシューティングゲームで、自機から「スペースを押している間だけいい感じの間隔で弾が発射できる」スクリプト
 発射間隔を調節する処理を入れないとすごい勢いで弾オブジェクトが生成されてしまうので注意。

スクリプト

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

public class PlayerScript : MonoBehaviour
{
    public GameObject bullet;
    private float interval = 0.2f; // 何秒間隔で撃つか
    private float timer = 0.0f; // 時間カウント用のタイマー

    void Start()
    {

    }

    void Update()
    {
        // 水平方向
        float dx = Input.GetAxis("Horizontal") * Time.deltaTime * 8f;
        // 垂直方向
        float dy = Input.GetAxis("Vertical") * Time.deltaTime * 8f;

        transform.position = new Vector3(
            // オブジェクトが移動できる範囲の制限
            Mathf.Clamp(transform.position.x + dx, -8.23f, 8.23f),
            Mathf.Clamp(transform.position.y + dy, -4.5f, 4.5f),
            0f
        );
        // スペースキーを押している間、一定間隔でbulletを打ち続ける
        if(Input.GetKey(KeyCode.Space) && timer <= 0.0f) // 分岐条件変更
        {
            Instantiate(bullet, transform.position, Quaternion.identity);
            timer = interval; // 間隔をセット
        }
        // タイマーの値を減らす
        if(timer > 0.0f)
        {
            timer -= Time.deltaTime;
        }
    }
}