【发布时间】:2021-04-09 20:51:55
【问题描述】:
在我的 Unity 游戏(自上而下的 2D 射击游戏)中,有一些敌人沿着一条路径飞行(通过 DOTween)。我的玩家将光线投射到场景中,以便在玩家面前获得一个敌方物体。到目前为止一切顺利。
现在的问题是我只想要一个敌方对象,即光线投射在第一次击中敌方对象时应该停止。我如何做到这一点?
我只需要一个被光线投射击中的敌人对象,因为我的游戏中有一个十字准线,当光线投射开始并且敌人沿着路径飞行时,十字准线会来回跳跃(我不希望这样 -准星应该停留在被光线投射击中的第一个敌人)。
这是我的代码(附在播放器上):
void FixedUpdate() {
//crosshair: Cast a ray straight up.
float _size = 12f;
Vector2 _direction = this.transform.up;
RaycastHit2D _hit = Physics2D.Raycast(this.transform.position, _direction, _size);
if (_hit.collider != null && _hit.collider.tag == "EnemyShipTag") {
// We touched something!
Vector2 target = new Vector2(_hit.collider.gameObject.transform.position.x, _hit.collider.gameObject.transform.position.y);
const float moveTime = 0.1f;
float step;
step = Vector2.Distance(crosshairGO.transform.position, target);
crosshairGO.transform.position = Vector2.MoveTowards(crosshairGO.transform.position, target, step / moveTime * Time.deltaTime);
Vector2 _pos3 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);
crosshairGO.transform.position = _pos3;
crosshairBegin = false;
} else {
// Nothing hit
Vector2 _pos2 = new Vector2(this.transform.position.x, 4.5f);
if (crosshairBegin) {
crosshairGO.transform.position = _pos2;
} else {
Vector2 _pos4 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);
crosshairGO.transform.position = _pos4;
}
}
}
【问题讨论】:
-
看看这个Unity forum answer。
-
是的,我知道这个线程,但我无法让它在我的情况下工作。我在我的代码中使用了以下代码-sn-p:RaycastHit hitPoint; Ray ray = Camera.main.ScreenPointToRay(this.transform.position); if (Physics.Raycast(ray, out hitPoint, Mathf.Infinity)) { if (hitPoint.collider.tag == "EnemyShipTag") { Debug.Log("Enemy object hit"); } } else { Debug.Log ("No collider hit");代码在我的情况下不起作用。有什么想法吗?
-
你确定它会击中多个敌人吗?还是每一帧都是同一个敌人?如果您希望它仅在第一次击中敌人时打印,那就不同了。
-
我现在明白我的问题了。我的敌人路径上有空隙,所以光线穿过空隙投射到后排。这就是他们跳来跳去的原因。
-
很高兴你知道了!
标签: c# unity3d game-physics