Unity2D光線の基本的な使用法と線画



Unity 2d Ray Basic Use



2D光線は、isTriggerオブジェクトなど、Collider2Dがマウントされているオブジェクトを検出できます。

光線を放出するオブジェクト自体にコライダーがある場合、光線はコライダーの内側から放出され、衝突を最初に検出するオブジェクトはそれ自体になります。



自分自身に戻りたくない場合は、設定で[Queries Start InCollider]のチェックを外すことができます。

isTriggerオブジェクトの衝突を検出したくない場合は、[クエリヒットトリガー]のチェックを外すことができます。



光線を定義します。

/ / Parameters are: starting point coordinates, direction vector Ray2D ray=new Ray2D( transform.position, Vector2.right )

光線を描く



Debug.DrawRay( ray.origin, ray.direction, Color.blue )//starting point, direction, color (optional) //The length of the line is the same as the ray, as the current ray direction vector is Vector2.right, the length is 1

光線衝突情報を取得します。

//Infinity RaycastHit2D info=Physics2D.Raycast(ray.origin, ray.direction) / / Or directly use the point coordinates, direction //RaycastHit2D info=Physics2D.Raycast( startPos, Vector2.right) / / Limit distance: RaycastHit2D info=Physics2D.Raycast( startPos, direction, 10f )

取得した光線衝突情報を使用して、衝突または衝突が発生したかどうかを判断します。

If(info.collider!=null){//if a collision has occurred GameObject obj=info.collider.gameObject If(obj.CompareTag('Enemy'))//Use the tag to determine what object was encountered Debug.Log(obj.name) }

完全な例:最初に遭遇したオブジェクトが敵であるかどうかを検出するために、光線がそれ自体の右側に放出されます。

using System.Collections using System.Collections.Generic using UnityEngine public class RayTest : MonoBehaviour { Ray2D ray void Update () { ray=new Ray2D(transform.position,Vector2.right) RaycastHit2D info=Physics2D.Raycast(ray.origin,ray.direction) //Debug.DrawRay(ray.origin,ray.direction,Color.blue) if(info.collider!=null){ if(info.transform.gameObject.CompareTag('Enemy')){ Debug.LogWarning('Detected Enemies') }else{ Debug.Log('Detected other objects') } }else{ Debug.Log('No collisions with any objects') } } }