Unity 使用Camera制作小地图显示,玩家可通过点击小地图到达任意位置

创建小地图显示的方法很多,各有千秋,最近项目需要用到小地图实时显示玩家的位置,并且玩家可通过点击小地图跳转到所点击的位置,因前期偷懒没有只考虑了显示玩家的位置并没有考虑小地图的可点击的情况,后来通过判断鼠标的位置来解决了这个问题,所以再次记录一下:

  1. 使用第二个相机创建小镜头,并通过调节ViewportRect的数值来控制显示的位置;

Viewport Rect

四个值表示这个摄像机视图将在屏幕上的哪个位置被绘制。在Viewport坐标中测量(值0-1)。

X

相机视图将被绘制的开始水平位置。

Y

相机视图将被绘制的开始垂直位置。

W (Width)

屏幕上相机输出的宽度。

H (Height)

摄像头在屏幕上输出的高度。

小地图左下角坐标可通过:

x= Screen.width * ViewportRect.rect.x;

y=Screen.height * ViewportRect.rect.y;

maxY= yMin + Screen.height * ViewportRect.rect.height;

maxX = xMin + Screen.width * ViewportRect.rect.width;

点击相应通过射线来触发;

具体代码如下:

public class MinDemo : MonoBehaviour

{

/// <summary>

/// 玩家

/// </summary>

public Transform Play;

/// <summary>

/// 小地图的相机

/// </summary>

public Camera minCam;

/// <summary>

/// 小地图是否可点击

/// </summary>

public bool minCamIsClick;

[HideInInspector]

/// <summary>

///记录小地图的最大以及最小坐标值

/// </summary>

public float xMin, xMax, yMin, yMax;

/// <summary>

/// 当前鼠标的坐标

/// </summary>

[HideInInspector]

public Vector2 mousePos;

void Update()

{

if (minCamIsClick)

if (minCam.gameObject.activeSelf == true)

{

if (Input.GetMouseButton(0))

{

//小镜头显示框的左下角坐标

xMin = Screen.width * minCam.rect.x;

yMin = Screen.height * minCam.rect.y;

//左下角的坐标加上相机视口的高度或宽度为最大坐标

yMax = yMin + Screen.height * minCam.rect.height;

xMax = xMin + Screen.width * minCam.rect.width;

mousePos = Input.mousePosition;

if (mousePos.x > xMin && mousePos.x < xMax && mousePos.y > yMin && mousePos.y < yMax)

{

Ray ray = minCam.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;

if (Physics.Raycast(ray, out hit))

{

Play.position = new Vector3(hit.point.x, Play.position.y, hit.point.z);

}

}

}

}

}

}

猜你喜欢

转载自blog.csdn.net/qq_23231303/article/details/128846747