end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

unityの OnCollisionEnter()による当たり判定

3D Sphereをカーソルキーで動かし、 他の 3D Sphere と衝突した場合、他の 3D Sphere を消去します。

Step 1 - 手玉となる 赤色 3D Sphere 追加

以下のように「Add Component」から「Rigidbody」を追加します。 尚、3D Sphereへの赤色設定方法は先日のentryをご覧ください。

Step 2 - 的玉となる 白色 3D Sphere 追加

先程と同様「Rigidbody」付で3D Sphere を追加し、 更に的玉と判定する為「Others」というタグを設定ます。

Step 3 - c# script作成

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

public class SampleSceneScript : MonoBehaviour {
    bool f = true;
    Vector3 cv = new Vector3(0f, 1f, -5f);
    Rigidbody rb = null;
    void Start(){
        rb = GetComponent<Rigidbody>();
    }

    void Update() {
        var sv = transform.position;
        sv.y = 1f;
        Camera.main.transform.position = sv + cv;
    //カーソルキーによる手玉の移動
        var x = Input.GetAxis("Horizontal");
        var y = Input.GetAxis("Vertical");
        var v = new Vector3(x, 0, y);

        rb.AddForce(v);
    }

    //衝突が発生した場合、「Others」を消去
    void OnCollisionEnter(Collision collision){
        if (collision.gameObject.tag == "Other"){
            GameObject.Destroy(collision.gameObject);
        }
    }
}