public Camera modelCamera;
RaycastHit hit;
Ray ray;
/// <summary>
/// 图层索引
/// </summary>
int layerIndex = 0;
//3d渲染在2d界面显示的内容
public RawImage rawImage;
//图片和屏幕的宽和高
public float imageWidth = 0;
public float imageHeight = 0;
public float screenWith = 0;
public float screenHeight = 0;
// Start is called before the first frame update
void Start()
{
layerIndex = LayerMask.GetMask("model");
screenWith = Screen.currentResolution.width;
screenHeight = Screen.currentResolution.height;
imageWidth = rawImage.rectTransform.rect.width;
imageHeight = rawImage.rectTransform.rect.height;
}
// Update is called once per frame
void Update()
{
Vector3 clickPosInRawImg = Input.mousePosition;
if (Input.GetMouseButton(0))
{
//(屏幕的宽度-承载图片的宽度)/2
//计算屏幕与承载图片宽和高的差值
float localDiffX = (screenWith - imageWidth) / 2.0f;
//(屏幕的高度-承载图片的高度)/2
float localDiffY = (screenHeight - imageHeight) / 2.0f;
//获取鼠标偏移后的位置
float xPoint = clickPosInRawImg.x - localDiffX;
float yPint = clickPosInRawImg.y - localDiffY;
//获取差集后的鼠标位置点,作为发射线的点
ray = modelCamera.ScreenPointToRay(new Vector2(xPoint, yPint));
if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerIndex))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
Debug.Log(hit.collider.name);
}
}
}