Tuesday, February 01, 2011

A 3D Skybox

A 3D skybox sits between your game world and the 2D skybox texture commonly used as a background for your scene.

Why do you need it?

It allows you to have 3D scenery in your background, which the player cannot interact with, yet is still effected by lighting, can use shaders and provide a much higher level of detail than the 2D skybox. This is how I do it in Unity3D.

using UnityEngine;
using System.Collections;

public class Skybox3D : MonoBehaviour {

public float levelScale = 32;

Camera skyCam;

void Start () {
var min = Vector3.zero;
var max = Vector3.zero;

foreach(Transform i in transform) {
i.gameObject.layer = gameObject.layer;
if(i.renderer == null) continue;
var bmax = i.renderer.bounds.max;
var bmin = i.renderer.bounds.min;
min.x = Mathf.Min(min.x, bmin.x);
min.y = Mathf.Min(min.y, bmin.y);
min.z = Mathf.Min(min.z, bmin.z);
max.x = Mathf.Max(max.x, bmax.x);
max.y = Mathf.Max(max.y, bmax.y);
max.z = Mathf.Max(max.z, bmax.z);

float absMax;
if(min.sqrMagnitude > max.sqrMagnitude)
absMax = min.magnitude * levelScale * 1.5f;
absMax = max.magnitude * levelScale * 1.5f;

transform.localScale = Vector3.one * levelScale;
skyCam = new GameObject("Sky Camera", typeof(Camera)).camera;
skyCam.transform.parent = Camera.main.transform;
skyCam.nearClipPlane = absMax / 3;
skyCam.farClipPlane = absMax;
skyCam.cullingMask = 1 << gameObject.layer;
skyCam.depth = Camera.main.depth - 1;
Camera.main.cullingMask ^= 1 << gameObject.layer;
if(Camera.main.clearFlags != CameraClearFlags.Depth) {
Debug.LogWarning("The main camera must have clear flags set to depth only.");

I build my 3D skybox as a child of an empty game object which has the above component attached. I build my skybox at a 1/32 scale, and in the component, I set the level scale to 32. This means that when I hit the play button, the 3D skybox is scaled up and moved out the extremities of my game level.


das said...

Does it allow for parallax ?

Simon Wittber said...

Yes, it is basically just a very large 3D object.

Scott said...

Do you run into any depth precision issues with this? I'd imagine that could be a problem at larger scales.

Simon Wittber said...

I haven't seen any depth problems. If there is, the sky box camera can be adjusted separately from the main camera to increase the resolution of the depth buffer.

Popular Posts