java - 将鼠标位置计算到 3d 空间 - OpenGL
问题描述
我正在尝试创建一条将鼠标坐标转换为 3d 世界坐标的射线。
Cx = Mx / screenWidth * 2 - 1
Cy = -( My / screenHeight * 2 - 1 )
vNear = InverseViewProjectionMatrix * ( Cx, Cy, -1, 1 )
VFar = InverseViewProjectionMatrix * ( Cx, Cy, 1, 1 )
vNear /= vNear.w
vFar /= vFar.w
测试光线的 vFar 后似乎总是来自相同的大致方向
似乎我需要添加相机视角,因为我希望 vFar 总是在我的相机后面。
我不完全确定应该如何添加。这是我的测试代码。
public void mouseToWorldCordinates(Window window,Camera camera, Vector2d mousePosition){
float normalised_x = (float)((mousePosition.x / (window.getWidth()*2)) -1);
float normalised_y = -(float)((mousePosition.y / (window.getHeight()*2)) -1);
Vector4f mouse = new Vector4f(normalised_x,normalised_y,-1,1);
Matrix4f projectionMatrix = new Matrix4f(transformation.getProjectionMatrix()).invert();
Matrix4f mouse4f = new Matrix4f(mouse,new Vector4f(),new Vector4f(),new Vector4f());
Matrix4f vNear4f = projectionMatrix.mul(mouse4f);
Vector4f vNear = new Vector4f();
vNear4f.getColumn(0,vNear);
mouse.z = 1f;
projectionMatrix = new Matrix4f(transformation.getProjectionMatrix()).invert();
mouse4f = new Matrix4f(mouse,new Vector4f(),new Vector4f(),new Vector4f());
Matrix4f vFar4f = projectionMatrix.mul(mouse4f);
Vector4f vFar = new Vector4f();
vFar4f.getColumn(0,vFar);
vNear.div(vNear.w);
vFar.div(vFar.w);
lines[0] = vNear.x;
lines[1] = vNear.y;
lines[2] = vNear.z;
lines[3] = vFar.x;
lines[4] = vFar.y;
lines[5] = vFar.z;
}
解决方案
normalised_x
和的计算normalised_y
是错误的。标准化设备坐标在 [-1.0, 1.0] 范围内:
float normalised_x = 2.0f * (float)mousePosition.x / (float)window.getWidth() - 1.0f;
float normalised_y = 1.0f - 2.0f * (float)mousePosition.y / (float)window.getHeight();
推荐阅读
- firebase - nuxtjs 项目中的 Firebase“无法解析”服务器中间件处理程序(“无法从“/workspace/graphql/index.js”解析“~/graphql/index.js”)
- javascript - 如何根据 ASP.NET Core 中的环境配置 fetch() URL?
- azure - 上传到 Azure 存储静态网站“$web”时 AzureFileCopyV4 失败
- java - Flink 反序列化 Schema 问题
- python - 跨数据子集计算列中类别的频率
- python - 使用函数迭代字典
- regex - 使用 Regex Extract 在 Google Data Studio 中分解管道分隔字符串并返回段
- selenium - 我正在尝试自动化 Flipkart,在尝试单击标题菜单的子菜单时,它正在与 DOM 分离,如何处理?
- javascript - 如何在 Webpack 5 中访问 process.env.VAR?
- ios - 在 iOS 上导入 ML Kit 依赖项