MENU

Unity学習メモ

f:id:spreadthec0ntents:20220318084607p:plain

Sceneをロードする

 画面を切り替える。

// シーンのロードをするときに必要な宣言
using UnityEngine.SceneManagement;

SceneManager.LoadScene("読み込みたいScene");

キー入力の受付

// Time.deltaTimeはマシンのスペック差を解消するための値
Input.GetAxis("Horizontal");

 オブジェクトをxとy軸方向にキー入力で移動させる。

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

        transform.position = new Vector3(
            transform.position.x + dx,
            transform.position.y + dy,
            0f
        );

 Mathf.Clampでオブジェクトの移動範囲を制限する。

        transform.position = new Vector3(
            // オブジェクトが移動できる範囲の制限
            Mathf.Clamp(transform.position.x + dx, -8f, 8f),
            Mathf.Clamp(transform.position.y + dy, -4.5f, 4.5f),
            0f
        );

衝突判定

    // hogeタグがついているオブジェクトと衝突したらオブジェクトを消滅させる
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("hoge"))
        {
            Destroy(gameObject);
        }
    }

オブジェクトの複製(prefab)

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

public class BallFactoryScript : MonoBehaviour
{
    public GameObject ball;

    void Start()
    {
        
        // 一定時間ごとに引数のメソッドを繰り返す(method, 開始時間(秒), 間隔(秒))
        InvokeRepeating("SpawnBall", 0f, 2f);
    }
    // ballのインスタンスを生成する
    void SpawnBall()
    {
        Instantiate(ball, new Vector3(Random.Range(-5f, 5f), transform.position.y, transform.position.z), transform.rotation);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}