[Unity実戦]画面追跡表示目標
4247 ワード
参照リンク:http://www.manew.com/thread-48125-1-1.html?_dsign=4 edc 9052
効果図:
効果図:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public enum BeaconMoveType
{
Rect, //
Rllipse, //
}
public class Beacon : MonoBehaviour {
private Transform player;
private Transform target;
private List<GameObject> targetList = new List<GameObject>();
private float width;
private float height;
public float range = 5f;// ,
public BeaconMoveType beaconMoveType;
public void SetTarget(Transform target)
{
this.target = target;
}
public void SetTarget()
{
if (targetList.Count > 0)
{
targetList.Sort((a, b) =>
{
float disA = MathTool.GetDistance(a.transform, player);
float disB = MathTool.GetDistance(b.transform, player);
return disA.CompareTo(disB);
});
float dis = MathTool.GetDistance(targetList[0].transform, player);
if (dis > range) target = targetList[0].transform;
else target = null;
}
}
void Start ()
{
player = CharacterManager.Instance.player.transform;
targetList = CharacterManager.Instance.enemyCampGo;
// , UI :
//x:-Screen.width / 2 - Screen.width / 2
//y:-Screen.height / 2 - Screen.height / 2
//50
width = Screen.width / 2 - 50;
height = Screen.height / 2 - 50;
}
void Update ()
{
SetTarget();
if ((player == null) || (target == null))
{
transform.localScale = Vector3.zero;//
return;
}
else
{
transform.localScale = Vector3.one;//
}
Vector3 dir = (target.position - player.position).normalized;
dir.y = 0;
float dot = Vector3.Dot(dir, Vector3.forward);// Vector3.forward
float angle = Mathf.Acos(dot) * Mathf.Rad2Deg;
Vector3 cross = Vector3.Cross(dir, Vector3.forward);//
//Debug.Log(" :" + angle + "---" + (cross.y > 0?" ":" "));
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle * (cross.y > 0 ? 1 : -1)));
Vector3 pos = Vector3.zero;
if (angle == 0) pos = new Vector3(0, height, 0);
else if (angle == 180) pos = new Vector3(0, -height, 0);
else
{
//1.
// x :x²/a²+ y²/b²=1 (a>b>0)
// y :y²/a²+ x²/b²=1 (a>b>0)
//2.k = x / y
//k 0-90 0,90-180 0
float k = Mathf.Tan(angle * Mathf.Deg2Rad);
k = Mathf.Abs(k);//
switch (beaconMoveType)
{
case BeaconMoveType.Rllipse:
pos.y = width * height * Mathf.Sqrt((1f / (width * width + height * height * k * k)));
pos.x = pos.y * k;
if (angle > 90f) pos.y = -pos.y;//
if (cross.y > 0f) pos.x = -pos.x;//
break;
case BeaconMoveType.Rect:
pos.x = height * k;
if ((pos.x > -width) && (pos.x < width))//
{
pos.y = height;
}
else//
{
pos.x = width;
if(k != 0f) pos.y = pos.x / k;
}
if (angle > 90f) pos.y = -pos.y;//
if (cross.y > 0f) pos.x = -pos.x;//
break;
default:
break;
}
}
transform.localPosition = pos;
}
}