オブジェクトの向いている方向に簡易的に台形状の視界範囲を表示するスクリプトです。
頂点が4つだけなので、端は正確ではありません。
カメラに写りやすいように正面側を強制的に向くようにしてあります
TargetSight にオブジェクトを
SightDirection にオブジェクトの正面方向のベクトルを入力して使います
DrawTrapezoidSight
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
public class DrawTrapezoidSight : MonoBehaviour
{
public GameObject TargetSight;
public Vector3 SightDirection = Vector3.up;
[Range(10, 170)]
public float Angle = 60;
[Range(0, 1)]
public float Thickness = 0.1f;
[Range(1.0f, 4.0f)]
public float Range = 4;
private Mesh mesh;
private Vector3[] vertices;
private int[] triangles;
private void Awake()
{
CreateMesh();
}
public void CreateMesh()
{
mesh = new Mesh();
GetComponent<MeshFilter>().mesh = mesh;
vertices = new Vector3[4];
triangles = new int[] { 0, 1, 2, 0, 2, 3, };
UpdateVertices();
}
public void UpdateVertices()
{
float sin = Mathf.Sin(Angle * 0.5f * Mathf.Deg2Rad);
float cos = Mathf.Cos(Angle * 0.5f * Mathf.Deg2Rad);
Vector3 v_left = new Vector3(-sin, 0, cos).normalized;
Vector3 v_right = new Vector3(sin, 0, cos).normalized;
float fix_range = Range;
if (cos != 0)
{
fix_range = Range / cos * Mathf.Sqrt(sin * sin + cos * cos);
}
vertices[0] = v_left * Thickness * 0.99f * fix_range;
vertices[1] = v_left * fix_range;
vertices[3] = v_right * Thickness * 0.99f * fix_range;
vertices[2] = v_right * fix_range;
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
private void UpdateSight()
{
transform.position = TargetSight.transform.position;
Vector3 direction = TargetSight.transform.TransformDirection(SightDirection);
Vector3 projected_direction = Vector3.ProjectOnPlane(direction, Vector3.back).normalized;
Quaternion rotation_to = Quaternion.LookRotation(projected_direction, Vector3.back);
transform.rotation = rotation_to;
}
// Update is called once per frame
void Update()
{
UpdateSight();
}
}
視界範囲用の単色とアルファのみのシェーダー
Shader
Shader "Unlit/UnliteColorTransparent"
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_Opacity("Opacity", Range(0, 1)) = 1
}
SubShader
{
Tags { "RenderType"="Transparent" "Queue" = "Transparent" }
LOD 200
Cull Off
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 vertex : SV_POSITION;
};
fixed4 _Color;
float _Opacity;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = _Color;
col.a=_Opacity;
return col;
}
ENDCG
}
}
}
↧