
ステルスゲージを作る #1 のゲージの値を変えてみました。敵からプレイヤーの頭へのレイが視界の範囲内で当たっているときにゲージを増やします。
まずゲージのImageコンポーネントのSource Imageに真っ白いスプライトをアタッチします。


Colorで色を変えられます。Image TypeをFilledにすると、Fill Amountが0のときに画像が全く表示されず、1の時に全体が表示されます。Fill MethodとFill Originで、どの位置からどの方向へ画像が埋まっていくかを設定できます。


敵からのレイが当たるようにプレイヤーの頭にコライダーを付けました。頭にはMainCameraタグが付いています。


障害物のCubeにもBoxコライダーを付けました。

そして、敵のスクリプトのUpdateメソッドでレイを飛ばして、レイが頭に当たると内積を計算します。内積が0より大きい時にゲージに値を足します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class TestAgent : MonoBehaviour
{
NavMeshAgent agent;
// ゲージ
public Gauge Gauge{ get; private set; }
// Start is called before the first frame update
void Start()
{
agent = GetComponent<NavMeshAgent>();
GoNextPoint();
}
// Update is called once per frame
void Update()
{
// 目的地に付いた時
if (!agent.pathPending && agent.remainingDistance < 0.5f)
{
// 次の目的地を設定
GoNextPoint();
}
// ゲージの位置と回転を変える
if(Gauge!= null) Gauge.ChangePosRot(transform);
// ゲージの値を増加
float gaugeAmount = -0.01f;
// 敵からプレイヤーへの方向
Vector3 dir = Camera.main.transform.position - transform.position;
RaycastHit hitInfo;
// プレイヤーの頭にレイを飛ばす
if (Physics.Raycast(transform.position, dir, out hitInfo, Mathf.Infinity))
{
// プレイヤーに当たった時
if(hitInfo.collider.tag == "MainCamera")
{
dir = Vector3.Normalize(dir);
float dot = Vector3.Dot(dir, transform.forward);
// 内積を足す
gaugeAmount += dot /10;
}
}
// ゲージの値を増加
Gauge.AddFillAmount(gaugeAmount);
}
// 次の目的地を設定
void GoNextPoint()
{
agent.destination = TestAgentFactory.GetInstance().GetRandomPoint().position;
}
// ...
}
また、ゲージのスクリプトで、ImageコンポーネントのfillAmountに値をセットするメソッドを作りました。ゲージの値を足す時に敵のスクリプトでこのメソッドを呼んでいます。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
public class Gauge : MonoBehaviour
{
RectTransform rt;
Image image;
private void Awake()
{
rt = GetComponent<RectTransform>();
image = GetComponent<Image>();
}
// ...
// ゲージを増やす
public void AddFillAmount(float fillAmount)
{
float a = image.fillAmount;
a += fillAmount;
image.fillAmount = Mathf.Clamp(a, 0f, 1f);
}
}
これでステルスゲージの値を変えられました。
