Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Unity3D Brick Shooter

0.00/5 (No votes)
19 Jan 2015CPOL1 min read 8.2K  
Unity3D Brick shooter

Followed this official tutorial, my own version on GitHub, and you can see it in action here (WSAD to move, mouse click to shoot).

Steps on how to create this:

  1. Create a new 3D project
  2. Save the scene as Main
  3. Create -> 3D object -> Plane
  4. Create -> 3D object -> Cube
    1. Add Component -> Physics -> Box collider
    2. Add Component -> Physics -> Rigidbody
    3. Drag and drop this object in the Assets/Prefabs folder
    4. Make duplicates (use snapping to move by using the ctrl key)
    5. Make a row of them (about 8) and then make a new empty object and drag them all into this object
    6. Now duplicate this object and position above (again by using snapping with ctrl key)
  5. Create -> 3D object -> Sphere
    1. Add Component -> Physics -> Sphere collider
    2. Add Component -> Physics -> Rigidbody
    3. Make it into a prefab
    4. Delete it from Hierarchy
  6. On the camera object => Add Component -> Script:
    1. JavaScript
      #pragma strict
      
      public var projectile : Rigidbody;
      public var shotPos : Transform;
      public var shotForce : float = 1000f;
      public var moveSpeed : float = 10f;
      
      function Update ()
      {
          var h : float = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
          var v : float = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
          
          transform.Translate(new Vector3(h, v, 0f));
          
          if(Input.GetButtonUp("Fire1"))
          {
              var shot : Rigidbody = Instantiate(projectile, shotPos.position, shotPos.rotation);
              shot.AddForce(shotPos.forward * shotForce);
          }
      }
    2. Drag the Sphere prefab to the projectile.
  7. Create empty game object and rename to shotPos.
    1. Drag and drop it on the camera
    2. Reset transform origin
    3. Position y=-0.5, z=1
    4. Rotation x=-15
  8. Drag Camera to shot pos variable in the script.
  9. If you want to clean up the bullets after 2 seconds, add script to Sphere prefab:
    JavaScript
    function Start () {
    	Destroy(gameObject, 2f);
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)