Canvas WorldToScreenPoint 스크립트


출처 : https://forum.unity.com/threads/create-ui-health-markers-like-in-world-of-tanks.432935/#post-2800360


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class WorldToScreenPoint : MonoBehaviour {
 
    public Transform target;
    public float yOffset = 1.5f;
    public RectTransform canvasRect; // 메인 캔버스
    public RectTransform markerRtra; // 캔버스 하위의 이동시킬 Rect (HP Bar 등)
    
    void Update ()
    {
        // Offset position above object bbox (in world space)
        float offsetPosY = target.transform.position.y + yOffset;
 
        // Final position of marker above GO in world space
        Vector3 offsetPos = new Vector3(target.transform.position.x, offsetPosY, target.transform.position.z);
 
        // Calculate *screen* position (note, not a canvas/recttransform position)
        Vector2 canvasPos;
        Vector2 screenPoint = Camera.main.WorldToScreenPoint(offsetPos);
 
        // Convert screen position to Canvas / RectTransform space <- leave camera null if Screen Space Overlay
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPoint, nullout canvasPos);
 
        // Set
        markerRtra.localPosition = canvasPos;
        Debug.Log(canvasPos);
    }
}
cs




댓글

Designed by JB FACTORY