赤外線レーザーセンサーを作る
赤外線センサー
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Infrared : MonoBehaviour
{
public AudioClip sound;
public float maxDistance = 50f;
private LineRenderer lr;
private AudioSource audioSource;
private void Start()
{
lr = GetComponent<LineRenderer>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
Debug.DrawRay(transform.position, transform.forward * maxDistance, Color.blue);
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
lr.SetPosition(0, ray.origin);
if(Physics.Raycast(ray, out hit, maxDistance))
{
lr.SetPosition(1, hit.point);
if(hit.transform.CompareTag("Player"))
{
print("侵入者発見");
// 警報音を鳴らす。
audioSource.clip = sound;
audioSource.Play();
}
}
else
{
lr.SetPosition(1, ray.origin + ray.direction * maxDistance);
}
}
}
【2019版】X_Mission(基礎/全51回)
他のコースを見る赤外線センサー
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Infrared : MonoBehaviour
{
public AudioClip sound;
public float maxDistance = 50f;
private LineRenderer lr;
private AudioSource audioSource;
private void Start()
{
lr = GetComponent<LineRenderer>();
audioSource = GetComponent<AudioSource>();
}
void Update()
{
Debug.DrawRay(transform.position, transform.forward * maxDistance, Color.blue);
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
lr.SetPosition(0, ray.origin);
if(Physics.Raycast(ray, out hit, maxDistance))
{
lr.SetPosition(1, hit.point);
if(hit.transform.CompareTag("Player"))
{
print("侵入者発見");
// 警報音を鳴らす。
audioSource.clip = sound;
audioSource.Play();
}
}
else
{
lr.SetPosition(1, ray.origin + ray.direction * maxDistance);
}
}
}
赤外線レーザーセンサーを作る