我将X Y Z坐标转换成屏幕X Y坐标有什么问题? [英] What is wrong with my conversion of X Y Z co-ordinates to screen X Y co-ordinates?
问题描述
我正在开发一个HTML5 Canvas演示球体在3D空间中弹跳。这是很容易做到的。每个球都有X,Y和Z坐标。这些坐标然后被转换为我在这里阅读的屏幕X和Y坐标。 http://answers.google.com/answers/threadview/id/496030.html
I am working on a HTML5 Canvas demo of spheres bouncing in 3D space. This is very simple to do. Each ball has X, Y, and Z co-ordinates. These co-ordinates are then converted into screen X and Y co-ordinates that I read here. http://answers.google.com/answers/threadview/id/496030.html
我从上述链接将XYZ坐标转换为X和Y的公式为
The formula that I got from the above link to convert X Y Z co-ordinates into X and Y is
screenX = (depth/(Z+depth)) * X
screenY = (depth/(Z+depth)) * Y
我已经在jsFiddle中演示了工作代码。 http://jsfiddle.net/xeMpv/
I have put a demonstration of the working code in jsFiddle here. http://jsfiddle.net/xeMpv/
但是有东西在这里。 结果我看起来像这样。你能告诉我我做错了什么?
But something is off here. The result I get looks like this. Can you tell me what I am doing wrong?
推荐答案
目前你的起源(origo)在左上角。要投影 x
和 y
,以便您的原点或此处:笛卡尔坐标 [0 ,0,0]
位于屏幕中央:
Currently your origin (origo) is in the top left corner. To project x
and y
so that your origin, or here: the Cartesian coordinate [0, 0, 0]
is in center of the screen:
f = fieldOfView / (viewDistance + z);
px = x * f + screenWidth * 0.5;
py = y * f + screenHeight * 0.5;
-
fieldOfView
c>c> viewDistance 翻译 z
值。 -
px
和py
。 fieldOfView
is related to focal distance, use for example 128 - 256.viewDistance
translatesz
values.px
andpy
are the projected 2D coordinates.
如果所有的坐标都是正的,他们将被绘制在原点的右侧/底部,所以你需要使用负值
If all your coordinates are positive they will be drawn on the right/bottom side of the origin so you need to use negative values to have something on the left/top side of it.
此外:您可以用 rect()$ c $替换行操作c> s,如果你将它们缓存到屏幕外的canvas上,你可以blit到主画布,而不是每次都清除和重绘,这样可以提高性能。
Additionally: you can replace the line operations with rect()
s and if you cache them to an off-screen canvas you can "blit" that to main canvas instead of clearing and re-drawing each time which gives you a little better performance.
这篇关于我将X Y Z坐标转换成屏幕X Y坐标有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!