50. Starting with 3D – through the looking glass
This is the first in a new series about 3D modeling, focused on creating a walkaround 3D map.
In this first post, I’ll talk about how the 3D screen differs from the usual 2D screen. No technicalities, I promise.
Codea is made up of at least 4 parts (that I know of)
.
Essentially, Codea integrates all these different parts and then adds its own functions to connect to the Apple iOS environment. It’s an awesome achievement.
However, it means that there can be anomalies and unexpected surprises when you move between libraries.
For example.
In Codea, we’re used to the x,y screen coordinates starting at 0,0 in the bottom left corner. And we are told that the z coordinate gives us 3D depth, so a z of 300 is out in front of us, and a z of -300 is the same distance behind us.
However, if you actually draw something out there, you’re in for a surprise. It will be a mirror image (ie back to front) image, and the x axis will seem to run from right to left. After fighting with this for a while, I discovered it is because OpenGL has 0,0 at bottom right of the screen, ie the x axis does run from right to left.
So how do you get the x axis to go the right way? Basically, by turning around 180 degrees and drawing everything behind you.
Imagine standing on a line that has numbers running from 10 at the left down to 1 at the right. If you turn and face behind you, the numbers on the line under your feet now run from 1 at the left to 10 at the right.
So what you do is change all your z (depth) values to negatives, to draw them behind you, then you tell Codea to look behind you (ie turn around). This may sound strange when you are used to having a fixed screen in front of you, but in 3D, you can draw in any direction.
Let’s see how this works. Run the code below, which should put an image on the right of your screen, and flick the LookBehindYou option on and off, to see the difference when you draw in front of you or behind you.
Crazy, huh?
Don’t worry about understanding the code itself, we’ll cover that soon. It’s not as scary as it may look. For now, just get used to the idea of looking behind you, because we’ll be doing that a lot.
function setup() parameter.boolean('LookBehindYou',false) local img=readImage('Small World:Icon') m=mesh() local i=m:addRect(0,0,img.width,img.height) m:setRectTex(i,0,0,1,1) m.texture=img end function draw() background(220) perspective(45,WIDTH/HEIGHT) z=400 view=500 if LookBehindYou then z=-z view=-view end camera(0,20,10,0,20,view,0,1,0) pushMatrix() translate(100,0,z) m:draw() popMatrix() end