统一鼠标位置到世界位置,但只是 Y 位置 [英] Unity mouse position to world position but just the Y pos

查看:74
本文介绍了统一鼠标位置到世界位置,但只是 Y 位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在 Unity 游戏引擎中制作一个小游戏,现在我无法完成它只是为了将鼠标的 y 位置转换为世界 y 位置.有什么想法可以解决这个问题吗?(在 c# 中编程)

Hello I am making a small game in the Unity game engine and now I cant get it done just to get the y position of my mouse to be converted to the world y position. Any ideas to solve this?(Programming in c#)

推荐答案

请记住,鼠标位置是 2D 点,但您正在投影到 3D 世界.因此,鼠标的 Y 坐标取决于世界中位置的 Z 坐标.或者换句话说,高度将根据世界空间中点的深度而不同.如果你想获得某个深度的位置,你可以这样做:

Keep in mind that the mouse position is a 2D point, but you are projecting into a 3D world. As such, the Y coordinate of the mouse depends on the Z coordinate of the position in the world. Or in other words, the height will be different depending on the depth of the point in world space. If you want to get the position at a certain depth you can just do:

Vector3 mousePos = Input.mousePosition;
mousePos.z = <depth>;
float y = Camera.main.ScreenToWorldPoint(mousePos).y;

或者您可以将 Ray 投影到世界中并使用第一个的位置它作为采样深度击中的东西:

Or you can project a Ray into the world and use the position of the first thing it hits as the depth to sample at:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
    float y = hit.point.y;
}

请注意,这种方法假设光线会击中某物.

Note that this approach assumes the Ray will hit something.

这篇关于统一鼠标位置到世界位置,但只是 Y 位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆