Ray
前回は実際に弾丸を飛ばしたが、目に見えないRay(光線)というのを飛ばす方法もよく用いられる。
今回はクリックした場所にRayを飛ばしてRayが衝突したコライダーを消すという処理を作ってみよう。
[作成手順]
画面にSphereを並べる
1.CreateEmptyから原点にSphereGeneratorを作成し、SphereGenerator.csを以下のように作成アタッチする。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SphereGenerator : MonoBehaviour {
void Start () {
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
GameObject obj = GameObject.CreatePrimitive (PrimitiveType.Sphere);
obj.transform.position = new Vector3 ((float)x,(float)y,0f );
}
}
}
}
カメラの調整
2.下図のようにtransformを設定する。

3.実行してみよう。画面に100個のSphereが並べば成功だ。
カメラにスクリプトの付与
4.今回はカメラに直接スクリプトを付与する。Shooter.csを以下のように作成しカメラに付与する。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray,out hit, 100f)) {
Destroy(hit.collider.gameObject);
}
/*
foreach(RaycastHit hit in Physics.RaycastAll(ray)) {
Destroy(hit.collider.gameObject);
}
*/
/*
foreach (RaycastHit hit in Physics.SphereCastAll(ray,3f)) {
Destroy(hit.collider.gameObject);
}
*/
}
}
}
実行
5.実行してみよう。クリックしたところのSphereが消えれば成功だ。
[補足]
RaycastHit構造体が何を保持するかは公式サイトに全部出ている。見ておくこと
https://docs.unity3d.com/ScriptReference/RaycastHit.html
コメント