P
P
Pragma Games2022-02-23 17:13:34
Unity
Pragma Games, 2022-02-23 17:13:34

How to show the direction to the enemy with an arrow?

Hello. Such a task. When an enemy is out of view of the camera, you need to display an arrow on the screen (Represented as a UI element) that will point in his direction. So far, there is such code that moves the arrow to the desired position on the edge of the screen. Can this code be simplified? Plus, I would like to know how to rotate the arrow in the direction of the

PS position. The rotation was done in this way

private void RotateToTargetPoint(Transform arrow,Vector3 screenPos, Vector3 target)
{
            var dir = target - screenPos;
            var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            arrow.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}


var screenPos = _camera.WorldToViewportPoint(enemy.transform.position); 
 
if(screenPos.x >= 0 && screenPos.x <= 1 && screenPos.y >= 0 && screenPos.y <= 1)
{
      continue;
}
 
var onScreenPos = new Vector2(screenPos.x-0.5f, screenPos.y-0.5f)*2; 
var max = Mathf.Max(Mathf.Abs(onScreenPos.x), Mathf.Abs(onScreenPos.y));
onScreenPos = (onScreenPos/(max*2))+new Vector2(0.5f, 0.5f); 
var screenPoint = _camera.ViewportToScreenPoint(onScreenPos);

RotateToTargetPoint(arrows.transform, screenPos, OnScreenPos);
arrow.position = screenPoint;

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question