You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BuildSystem {
public class MouseClick : MonoBehaviour
{
public Transform ground;
public Camera camera;
RaycastHit raycastHit;
/// <summary>
/// 返回鼠标在地图上的坐标
/// </summary>
/// <returns></returns>
public Vector3Int MouseInGrid() {
Vector3 groundPos = camera.WorldToScreenPoint(ground.transform.position);
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, groundPos.z);
Vector3 worldMousePos = camera.ScreenToWorldPoint(mousePos);
Ray ray = new Ray(camera.transform.position, worldMousePos - camera.transform.position);
//Debug.DrawRay(camera.transform.position, worldMousePos - camera.transform.position,Color.blue);
int layerMask = (1 << 8) | (1 << 10);
layerMask = ~layerMask; //取消obj层防止遮挡
if (Physics.Raycast(ray, out raycastHit,1000f ,layerMask))
{
if (raycastHit.collider.tag == "Map")
{
//Debug.Log(WorldInGrid(raycastHit.point));
return WorldInGrid(raycastHit.point);
}
}
return new Vector3Int(-1,-1,-1);
}
/// <summary>
/// 给定一个世界坐标判断坐标位于哪个grid
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
Vector3Int WorldInGrid(Vector3 pos)
{
Vector3 gridSpace = pos - BuildSystemManager.Instance.startPos;
int x = (int)(gridSpace.x / BuildSystemManager.Instance.gridSize);
int z = (int)(gridSpace.z / BuildSystemManager.Instance.gridSize);
return new Vector3Int(x,0,z);
}
}
}