XNA2.0系统API居然出错!折腾了我N久。现象是鼠标射线不准,莫名其妙的不准,有时旋转一下相机就乱了,在官网论坛上找了一个替代版本,问题解决。这个问题XNA1.0并不存在,到2.0就有了,用反编译查看,果然是XNA1.0使用DX实现,XNA2.0是重写的方法。这个问题XNA论坛都提出来了,ViewPort.Unproject也算是一个比较重要的方法,居然到XNA3.0还存在,真不知道开发人员是怎么想的,为这个破问题折腾来折腾去,先前以为是相机问题,重写了好多遍,看来即使是官方API也不要过于迷信,这回主要就栽在这点。
经验总结:代码使人写的,不是神写的,人写的就会出错,就这么简单。最后附上可用的代替版本,看有多少可怜的孩子还在受到原API的毒害…
Code
1 public static Vector3 UnprojectEx(Viewport viewport, Vector3 screenSpace,Matrix projection, Matrix view, Matrix world)
2 {
3 //First, convert raw screen coords to unprojectable ones
4 Vector3 position = new Vector3();
5 position.X = (((screenSpace.X - (float)viewport.X) / ((float)viewport.Width)) * 2f) - 1f;
6 position.Y = -((((screenSpace.Y - (float)viewport.Y) / ((float)viewport.Height)) * 2f) - 1f);
7 position.Z = (screenSpace.Z - viewport.MinDepth) / (viewport.MaxDepth - viewport.MinDepth);
8
9 //Unproject by transforming the 4d vector by the inverse of the projecttion matrix,
10 //followed by the inverse of the view matrix.
11 Vector4 us4 = new Vector4(position, 1f);
12 Vector4 up4 = Vector4.Transform(us4,
13 Matrix.Invert(Matrix.Multiply(Matrix.Multiply(world, view), projection)));
14 Vector3 up3 = new Vector3(up4.X, up4.Y, up4.Z);
15 return up3 / up4.W; //better to do this here to reduce precision loss..
16 }
转载请注明出处:
作者:gogoplayer
E-mail : gogoplayer@163.com
QQ : 78939328
http://www.gogoplayer.com.cn