Unity 地图映射

思路

位置映射

地形 2261*3 = 6783

地图 2560

原点在地形正中心

映射比例为 (6783/2) / (2560/2) = 3391.5 / 1280 = 2.65

方向映射

先求出玩家与z轴的夹角

如下图所示

把夹角映射到画布上,让坐标指向对应的方向

比如,玩家指向x轴正向,坐标就应该绕z轴的反方向顺时针旋转90度

 

代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Mapping:MonoSingleton<Mapping>
{
    [Header("地形及地图信息")]
    public float terrainHeight;
    public float terrainWidth;
    public float mapHeight;
    public float mapWidth;

    //映射比率
    float heightConvertRate => terrainHeight / mapHeight;
    float widthConvertRate => terrainWidth / mapWidth;

    public Vector2 GetLocationInMap(Vector3 position)
    {
        return new Vector2(position.x / widthConvertRate, position.z / heightConvertRate);
    }

    public void UpdateLocationOnMap(Vector3 position)
    {
        locationPoint.GetComponent<RectTransform>().anchoredPosition = GetLocationInMap(position);
        locationPoint.transform.rotation = GetRotationFromDirection(player.forward);
    }

    void Update()
    {
        UpdateLocationOnMap(player.position);

        //考虑到切换角色,这里暂时偷个懒,后期可以在切换角色时调用
        Init();
    }

    //在游戏中可能发生变化的
    Transform player;
    Transform map;
    GameObject locationPoint;
    public void Init()
    {
        if (player == null)
            player = GameObject.FindGameObjectWithTag("Player").transform;

        if (map == null)
            map = GameObject.Find("Map").transform;

        if (locationPoint == null)
        {
            locationPoint = new GameObject("location");
            locationPoint.transform.SetParent(map);
            locationPoint.AddComponent(typeof(Image));
            locationPoint.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            locationPoint.GetComponent<RectTransform>().anchoredPosition = GetLocationInMap(player.position);
        }
    }

    //不变的
    public Texture2D texture;
    void Awake()
    {
        Init();
    }

    //绕z轴旋转到给定方向
    public float yaw;
    Quaternion GetRotationFromDirection(Vector3 direction)
    {
        yaw = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;            //玩家朝向与z轴的夹角
        return Quaternion.Euler(0, 0, -yaw);                                    //在画布上绕z轴的负方向旋转
    }
}

效果

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/124554482