Adding a background

There is still a lot of black in the background and as the game has a space theme, let's add some stars in there. The way we'll do this is to add a sphere that we can map the stars texture to, so click on Game Object | Create Other | Sphere, and position it at X: 0, Y: 0, Z: 0. We also need to set the size to X: 100, Y: 100, Z: 100. Drag the stars texture, located at Textures/stars, on to the new sphere that we created in our scene. That was simple, wasn't that? Unity has added the texture to a material that appears on the outside of our sphere while we need it to show on the inside. To fix it, we are going to reverse the triangle order, flip the normal map, and flip the UV map with C# code. Right-click on the Scripts folder and then click on Create and select C# Script. Once you click on it, a script will appear in the Scripts folder; it should already have focus and be asking you to type a name for the script, call it SkyDome. Double-click on the script in Unity and it will open in MonoDevelop. Edit the Start method, as shown in the following code:

void Start () {
  
  // Get a reference to the mesh
  MeshFilterBase MeshFilter = transform.GetComponent("MeshFilter") as MeshFilter;
  Mesh mesh = BaseMeshFilter.mesh;
  
  // Reverse triangle winding
  int[] triangles = mesh.triangles; 
  int numpolies = triangles.Length / 3;
  for(int t = 0;t <numpolies; t++)
  {
    Int tribuffer = triangles[t * 3];
    triangles[t * 3] = triangles[(t * 3) + 2];
    triangles[(t * 3) + 2] = tribuffer;
  }
  
  // Read just uv map for inner sphere projection
  Vector2[] uvs = mesh.uv;
  for(int uvnum = 0; uvnum < uvs.Length; uvnum++)
  {
    uvs[uvnum] = new Vector2(1 - uvs[uvnum].x, uvs[uvnum].y);
  }
  
  // Read just normals for inner sphere projection 
  Vector3[] norms = mesh.normals;       
  for(int normalsnum = 0; normalsnum < norms.Length; normalsnum++)
  {
    norms[normalsnum] = -norms[normalsnum];
  }
  
  // Copy local built in arrays back to the mesh
  mesh.uv = uvs;
  mesh.triangles = triangles;
  mesh.normals = norms;    
}  

The breakdown of the code as is follows:

  1. Get the mesh of the sphere.
  2. Reverse the way the triangles are drawn. Each triangle has three indexes in the array; this script just swaps the first and last index of each triangle in the array.
  3. Adjust the X position for the UV map coordinates.
  4. Flip the normals of the sphere.
  5. Apply the new values of the reversed triangles, adjusted UV coordinates, and flipped normals to the sphere.

Click and drag this script onto your sphere GameObject and test your scene. You should now see something like the following screenshot:

Adding a background
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.133