雷达地图

作者:追风剑情 发布于:2020-3-30 17:57 分类:Unity3d

1111.png

Map、Background、Player的Anchors都设置成左下角。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 雷达地图 (主界面右上角的小地图)
/// </summary>
public class UIRadarMap : MonoBehaviour
{
    public Image background;
    public Image mask;
    public Image playerIcon;
    private Transform player;
    private Terrain terrain;
    private float terrainWidth = 100;
    private float terrainLength = 100;
    private float radarWidth = 100;
    private float radarHeight = 100;
    private float radarWidthHalf = 50;
    private float radarHeightHalf = 50;
    private float scaleWidth = 1;
    private float scaleLength = 1;
    private Vector3 playerPosition;

    void Start()
    {
        GameObject go = GameObject.FindGameObjectWithTag("Terrain");
        if (go != null)
        {
            terrain = go.GetComponent<Terrain>();
            float size_x = terrain.terrainData.size.x;
            float size_y = terrain.terrainData.size.y;
            float size_z = terrain.terrainData.size.z;
            Debug.LogFormat("Terrain x={0}, y={1}, z={2}", size_x, size_y, size_z);
            terrainWidth = size_x;
            terrainLength = size_z;
            scaleWidth = background.rectTransform.sizeDelta.x / terrainWidth;
            scaleLength = background.rectTransform.sizeDelta.y / terrainLength;
        }
        radarWidth = mask.rectTransform.sizeDelta.x;
        radarHeight = mask.rectTransform.sizeDelta.y;
        radarWidthHalf = radarWidth / 2;
        radarHeightHalf = radarHeight / 2;

        player = PlayerController.Instance.transform;
    }

    void Update()
    {
        playerPosition = player.position;
        float px = playerPosition.x * scaleWidth;
        float py = playerPosition.z * scaleLength;
        playerIcon.rectTransform.anchoredPosition = new Vector2(px, py);

        float offsetX = px > radarWidthHalf ? radarWidthHalf - px : 0;
        float offsetY = py > radarHeightHalf ? radarHeightHalf - py : 0;
        background.rectTransform.anchoredPosition = new Vector2(offsetX, offsetY);
    }
}

运行效果

554.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号