首页 > 解决方案 > Unity offscreen target indicator-how to show the way to an object with a specific tag?

问题描述

UNITY 2D C#

Hi everyone. I have a script that allows the arrow to show where the point is .

My problem:

1) I would like the arrow to show the way to a point with a specific tag or name.

How to do it?

Because now, shows the way to the point (-50,0).

Could anyone help me transform the script?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CodeMonkey.Utils;


public class Window_QuestPointer : MonoBehaviour {

[SerializeField] private Camera uiCamera;



private Vector3 targetPosition;
private RectTransform pointerRectTransform;

private void Awake ()
{
    targetPosition = new Vector3 (-50, 0);
    pointerRectTransform = transform.Find ("Pointer").GetComponent<RectTransform> ();
}
private void Update (){
    Vector3 toPosition = targetPosition;
    Vector3 fromPosition = Camera.main.transform.position;
    fromPosition.z = 0f;
    Vector3 dir = (toPosition - fromPosition).normalized;
    float angle = UtilsClass.GetAngleFromVectorFloat(dir);
    pointerRectTransform.localEulerAngles = new Vector3 (0, 0, angle);

    float borderSize = 40f;

    Vector3 targetPositionScreenPoint = Camera.main.WorldToScreenPoint (targetPosition);
    bool isOffscreen = targetPositionScreenPoint.x <= borderSize || targetPositionScreenPoint.x >= Screen.width - borderSize || targetPositionScreenPoint.y <= borderSize || targetPositionScreenPoint.y >= Screen.height - borderSize;
    Debug.Log (isOffscreen + " " + targetPositionScreenPoint);

    if(isOffscreen){
        Vector3 cappedTargetScreenPosition = targetPositionScreenPoint;
        cappedTargetScreenPosition.x = Mathf.Clamp (cappedTargetScreenPosition.x, borderSize, Screen.width - borderSize);
        cappedTargetScreenPosition.y = Mathf.Clamp (cappedTargetScreenPosition.y, borderSize, Screen.height - borderSize);

        Vector3 pointerWorldPosition = uiCamera.ScreenToWorldPoint (cappedTargetScreenPosition);
        pointerRectTransform.position = pointerWorldPosition;
        pointerRectTransform.localPosition = new Vector3 (pointerRectTransform.localPosition.x, pointerRectTransform.localPosition.y, 0f);

    }
    else{
        Vector3 pointerWorldPosition = uiCamera.ScreenToWorldPoint (targetPositionScreenPoint);
        pointerRectTransform.position = pointerWorldPosition;
        pointerRectTransform.localPosition = new Vector3 (pointerRectTransform.localPosition.x, pointerRectTransform.localPosition.y, 0f);

}

} }

标签: unity3dindicatoroff-screen

解决方案


  1. Tag the item "target"

  2. Add this to end of Awake method to fetch target

    Void Awake(){ Transform offscreen = GameObject.FindGameObjectWithTag("target").GetComponent(); TargetPosition=offscreen.position; }

Should do the trick. I typed this on my phone so it should be close pseudo. Let me know!


推荐阅读