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

1 year ago
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BuildSystem {
public class MouseClick : MonoBehaviour
{
1 year ago
1 year ago
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);
1 year ago
//Debug.DrawRay(camera.transform.position, worldMousePos - camera.transform.position,Color.blue);
int layerMask = (1 << 8) | (1 << 10);
1 year ago
layerMask = ~layerMask; //取消obj层防止遮挡
if (Physics.Raycast(ray, out raycastHit,1000f ,layerMask))
{
if (raycastHit.collider.tag == "Map")
{
1 year ago
//Debug.Log(WorldInGrid(raycastHit.point));
1 year ago
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);
}
}
}