Skip to content

139. 3D sky

December 5, 2013

This post is about adding a 360 degree (and overhead) background to a 3D scene, so no matter which way you turn, you can see sky and horizon.

The simplest approach, which I am going to use here, is to create a sphere and wrap an image around it, then put the camera inside the sphere. We only need an image for the top half of the sphere, because the rest is out of sight, below our feet.

There isn’t a lot of code, except for creating the sphere (and I will just use Jmv38’s code for this),

Preparing the image

The image you will wrap onto the sphere needs to be twice as wide as it is tall, and it can’t be bigger than 2048 pixels wide. You should look for images specially created for this purpose (eg google for “sky dome” images), because normal images will get very distorted at the top of the sphere.

Since we only need the top half of the sphere, you should look for images that are 4 x wider than they are tall.

I found an image that was the right shape (width = 4 x height) but was too big, so I used Paint.Net to reduce the width to 2048 pixels. You can find my modified image here – save it to your Codea Dropbox account as SkyDome2.jpg.

The good news is that you have now done most of the work. Now we load the image into img, then create a new img2 which is the right shape for the sphere, ieĀ  twice as wide as it is tall, and draw img1 onto it at the top.

img1=readImage("Dropbox:SkyDome2")
img2=image(img1.width,img1.width/2)
setContext(img2)
spriteMode(CORNER)
sprite(img1,0,img2.height-img1.height)
setContext()

If your image is exactly 4 x wider than it is tall, then the result is an image where only the top half has a picture (which is what we want). If your image is a bit too tall, then some of it will be drawn in the bottom half of img2, which will be out of sight.

The rest of the work

Now I just create a sphere using code from Jmv38 and attach the image texture. Jmv38 included some code to make the sphere spin, so I left that in, so the world rotates when the app runs. (Normally, of course, you wouldn’t rotate the sphere – you’d rotate the camera!).

You may need to adjust the camera angle so you can’t see the missing bottom half of the picture, but most of the time, you will have some kind of surface in your scene which will probably hide it anyway.

It runs fast, too, at close to 60 frames per second, so it should be possible to include this in a game without slowing things down.

Advertisements

From → 3D, Graphics

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: