zoukankan      html  css  js  c++  java
  • UGUI世界坐标转换为UI本地坐标

    以下是实现hud跟随3D物体的脚本,只是测试用,不是开发中的代码,脚本挂在任意游戏物体上 demo下载

    using UnityEngine;

    public class SceneFollowUI : MonoBehaviour
    {
    public RectTransform hud; //Hud
    public RectTransform canvas;//UI的父节点
    public Transform parent; //跟随的3D物体
    public Camera uiCamera; //UICamera

    Vector3 offset; //hud偏移量
    Vector3 cachePoint;
    float originalDistance;
    float factor = 1;
    bool visiable = true;

    void Start()
    {
    offset = hud.localPosition - WorldPointToUILocalPoint(parent.position);
    cachePoint = parent.position;
    originalDistance = GetCameraHudRootDistance();
    UpdateVisible();
    }

    void LateUpdate()
    {
    if (cachePoint != parent.position)
    {
    float curDistance = GetCameraHudRootDistance();
    factor = originalDistance / curDistance;
    UpdatePosition(); //更新Hud位置
    UpdateScale(); //更新Hud的大小
    UpdateVisible(); //更新Hud是否可见,根据需求设置:factor或者根据和相机距离设置,一定范围内可见,相机视野范围内可见 等等
    }
    }


    private void UpdateVisible()
    {

    }

    private void UpdatePosition()
    {
    hud.localPosition = WorldPointToUILocalPoint(parent.position) + offset * factor;
    cachePoint = parent.position;
    }

    private void UpdateScale()
    {
    hud.localScale = Vector3.one * factor;
    }

    private float GetCameraHudRootDistance()
    {
    return Vector3.Distance(Camera.main.transform.position, parent.position);
    }

    private Vector3 WorldPointToUILocalPoint(Vector3 point)
    {
    Vector3 screenPoint = Camera.main.WorldToScreenPoint(point);
    Vector2 localPoint;
    RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, screenPoint, uiCamera, out localPoint);
    return localPoint;
    }
    }

  • 相关阅读:
    log4j2 标签解析
    7.3
    work-7.2
    爬取豆瓣上某个用户标记的想读的或者读过的图书信息
    python爬虫程序打包为exe程序并在控制台下运行
    爬取任意两个用户在豆瓣上标记的想读的图书信息的交集
    解决c# progressBar更新出现界面假死
    数据库死锁(大神请路过)
    Excel的下载和读取,部分代码(大神请路过)
    大数据缓存:redis
  • 原文地址:https://www.cnblogs.com/hyhy904/p/11044477.html
Copyright © 2011-2022 走看看