最近要準備 Paper Reading 的報告,有點忙與緊張哈哈哈,所以今天就針對簡單的小功能說明。
在遊戲環境中,我們需要知道 Player 視角看出的角度與距離是否包含任何敵人,或是電腦設定的敵人也會在可視的角度與距離內產生一些特定的反應或可攻擊的範圍等,我們可以當作是一個可視的範圍等,那這裡就先以簡單的實作開始。
今天我們會說明到常見的 Vector3.Angle 與 Vector3.Distance 常見的使用方式。並且說明變更某物件上顏色 Material 的方法。今天的解說會用到非常實用的方法,就讓我開始介紹。
public float angleRange = 60f;
public float distanceRange = 2f;
public Transform Player, Enemy;
void detectEnemy()
{
distance = Vector3.Distance(Player.position, Enemy.position);
angle = Vector3.Angle(Player.forward, Enemy.position - Player.position);
Debug.Log("Distance: " + distance + ", Angle: " + angle);
if(distance < distanceRange)
{
if(angle < angleRange)
{
seeTarget = true;
}else{
seeTarget = false;
}
}else{
seeTarget = false;
}
}
// change the object color from the enemy object
if(seeTarget)
{
Enemy.GetComponent<Renderer>().material.color = Color.red;
}else{
Enemy.GetComponent<Renderer>().material.color = Color.blue;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFieldView : MonoBehaviour
{
public float radius, angle;
private float distance;
GameObject ob;
MeshFilter meshFilter;
MeshRenderer meshRenderer;
Shader shader;
public float angleRange = 60f;
public float distanceRange = 2f;
// set the enemy object and player object
public Transform Player, Enemy;
bool seeTarget = false;
// The main driver function
void Update()
{
detectEnemy();
}
void detectEnemy()
{
distance = Vector3.Distance(Player.position, Enemy.position);
angle = Vector3.Angle(Player.forward, Enemy.position - Player.position);
Debug.Log("Distance: " + distance + ", Angle: " + angle);
if(distance < distanceRange)
{
if(angle < angleRange)
{
seeTarget = true;
}else{
seeTarget = false;
}
}else{
seeTarget = false;
}
// change the object color from the enemy object
if(seeTarget)
{
Enemy.GetComponent<Renderer>().material.color = Color.red;
Debug.LogWarning("Set!");
}else{
Enemy.GetComponent<Renderer>().material.color = Color.blue;
}
}
}
會看到說當 Enemy 沒有在 Player 的視角內為藍色。可以觀察到目前 Console 顯示的角度與距離
我們將Player 拉近到與Enemy 再近一點的話,Enemy就會變為紅色。可以觀察目前 Console 顯示的角度與距離。