Placing a cube on the face of another

Something like minecraft

place this script inside your scene with a cube and click play :

 void Update () {



        if ( Input.GetMouseButtonDown( 0 ) )
        {
            Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
            RaycastHit hit;
            if ( Physics.Raycast( ray , out hit , 2000 ) )
            {
                // it's better to find the center of the face like this:
                Vector3 position = hit.transform.position + hit.normal ;

                // calculate the rotation to create the object aligned with the face normal:
                Quaternion rotation =  Quaternion.FromToRotation( Vector3.up , hit.normal );
                // create the object at the face center, and perpendicular to it:
                GameObject Placement = GameObject.CreatePrimitive( PrimitiveType.Cube );
                Placement.transform.position = position;
                Placement.transform.rotation = rotation;



                //Instantiate<( PrimitiveType.Cube as GameObject , position , rotation ) as GameObject;
            }
            else
            {
                Debug.Log( "nothing" );
            }
        }


    }

Not the most descriptive question I’ve seen… However, if you want some working example, here’s a package I wrote some time ago, and I even have a blog post regarding some thoughts about it.

It contains a scene and scripts to generate voxels.

alt text

To do what you’ve asked, “place a block on the face I click on”, here’s what you will need:

http://unity3d.com/support/documentation/ScriptReference/Input-mousePosition.html

http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenPointToRay.html

Collider.Raycast

(as well as http://unity3d.com/support/documentation/ScriptReference/RaycastHit.html for point and normal)

Object.Instantiate

Good luck!

I made a prefab out of cubes that are allready in unity and this is a code to spawn them in 2D grid. There is also few lines which make middle tile pruple and align camera to the center:

var tilePrefab : GameObject;
var y : int = 10; 
var x : int = 10; 
var initialColor : Color;

function Start (){
  for (var i : int = 0;i < y; i++) {
    for (var j : int = 0; j < x; j++)
    {
      var tile : GameObject = Instantiate (tilePrefab, Vector3(j, i, 0), Quaternion.identity);
      if (i == y/2 && j == x/2)
      {
        print("test");
        var pos: Vector3 = tile.transform.position; // get the tile position...
        pos.z = Camera.main.transform.position.z; // but keep the camera z 
        Camera.main.transform.position = pos; // move camera to the position
        tile.renderer.material.color = Color.cyan;
8//,b
      }
    }
  }
}