我正在尝试使用光线投射来显示正确的光标,而不是观察敌人。我遇到了一些问题,因为它只是在直线上直接盯着敌人时才起作用,所以我检查了Debug.DrawRay,然后打开调试线,在我的块顶上看了一圈,然后关闭调试,找到这个奇怪的 -
看起来它并没有尝试在对角线上进行光线投射,这让我很困惑。
using UnityEngine;
public class CameraRaycaster : MonoBehaviour
{
public Layer[] LayerPriorities = {
Layer.Wall,
Layer.Enemy,
Layer.Walkable,
};
[SerializeField]
private float _distanceToBackground = 100f;
[SerializeField]
private GameObject _raycastObject;
public bool Debug = false;
public Layer DebugLayer = Layer.RaycastEndStop;
private Camera _viewCamera;
private RaycastHit _hit;
public RaycastHit Hit
{
get { return _hit; }
}
Layer _layerHit;
public Layer LayerHit
{
get { return _layerHit; }
}
private void Start() // TODO Awake?
{
_viewCamera = Camera.main;
}
private void Update()
{
// Look for and return priority layer hit
foreach (var layer in LayerPriorities)
{
var hit = RaycastForLayer(layer);
if (hit.HasValue)
{
_hit = hit.Value;
_layerHit = layer;
return;
}
}
// Otherwise return background hit
_hit.distance = _distanceToBackground;
_layerHit = Layer.RaycastEndStop;
}
private RaycastHit? RaycastForLayer(Layer layer)
{
var trans = this.transform;
if (_raycastObject != null)
{
trans = _raycastObject.transform;
}
var layerMask = 1 << (int)layer; // See Unity docs for mask formation
//Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit; // used as an out parameter
var hasHit = Physics.Raycast(trans.position, trans.forward, out hit, _distanceToBackground,layerMask);
if (Debug && (DebugLayer==Layer.RaycastEndStop || DebugLayer==layer))
{
var debugColour=hasHit?Color.green:Color.red;
UnityEngine.Debug.DrawRay(trans.position, trans.forward,debugColour,_distanceToBackground,true);
}
if (hasHit)
{
return hit;
}
return null;
}
}