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:
- Create a new 3D project
- Save the scene as
Main
- Create -> 3D object -> Plane
- Create -> 3D object -> Cube
- Add Component -> Physics -> Box collider
- Add Component -> Physics -> Rigidbody
- Drag and drop this object in the Assets/Prefabs folder
- Make duplicates (use snapping to move by using the ctrl key)
- Make a row of them (about 8) and then make a new empty object and drag them all into this object
- Now duplicate this object and position above (again by using snapping with ctrl key)
- Create -> 3D object -> Sphere
- Add Component -> Physics -> Sphere collider
- Add Component -> Physics ->
Rigidbody
- Make it into a prefab
- Delete it from Hierarchy
- On the
camera
object => Add Component -> Script:
-
#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);
}
}
- Drag the Sphere prefab to the projectile.
- Create empty game object and rename to
shotPos
.
- Drag and drop it on the camera
- Reset transform origin
- Position y=-0.5, z=1
- Rotation x=-15
- Drag Camera to shot pos variable in the script.
- If you want to clean up the bullets after 2 seconds, add script to Sphere prefab:
function Start () {
Destroy(gameObject, 2f);
}