I have 40 points with (x, y, z) coordinate in my iPhone app. For now I just NSLog them. But I'd like to display them in... 3D!
How can I do that? Do I have to use openGL ES? What are the others possibilities (if there are any)? I've 开发者_StackOverflow中文版never used 3D in programming... is this a difficult thing to do?Thanks !
You could do your own 3-D math and render to a 2-D surface using the CGContext drawing API, or you could use OpenGL ES to do the transformations and rendering for you. Both options have pros and cons, and they both have a learning curve.
I recommend the OpenGL option because the end result will be simpler and faster, and the skills you pick up will be more reusable.
Let me give a really simple description of a hard-wired setup that could get you started if you just want to draw points without learning any new APIs.
Let's suppose a camera with a 90 degree field of view. And let's assume you want to draw into a square window of width and height w
. Interpret the z
coordinate as distance 'into' the screen.
Then you plot the point (x,y,z)
at coordinates (X,Y)
given by
X = w/2+w/2*x/z
Y = w/2+w/2*y/z
The w/2+
bit is an offset to the centre of your window. The w/2*
bit is a scaling to make your 90 degree field of view fill the window. The /z
but is a scaling that makes more distant things seem smaller. That's it!
There are some things to watch out for though. If z <= 0
then you don't want to draw that point because it's behind the camera, or worse, in the plane of the screen resulting division by zero. And you might want to check that X
and Y
are in range before drawing. If not, then you'll be trying to draw points that are outside of your field of view.
Of course OpenGL can do much of this automatically for you, and it allows you to vary the camera, draw more than just points, rotate the points, as well as doing it all very fast. But it's good to learn the principles first.
(BTW A common convention is to draw only points with z<0
instead of z>0
. In that case you'd need to replace +
with -
sign in the above code.)
(Fixed typo. Thanks for pointing it out!)
If you are going to display the points in 3D and do your own math, it is quite simple, as long as they are all points and you are looking straight at one of the axis. The math is simple and you can use something like this to get started:
http://www.cleverpig.com/tutorials/starfield/
Now, if you want to use a more realistic perspective projection, draw lines, 3d objects, play with the "camera" or do complex animations, OpenGL ES will be indicated.
精彩评论