Unity – Spaceship Shooting Game – JS – Spaceship

1. Hierarchy> select the Space Ship GameObject> Inspector> ‘Add Component’> Scripts> JS Script

The code of ‘PlayerController.js’:

#pragma strict

class Boundary
{
    // Theese variables are public to make the code easy-reusable
    // You can setup theese variables from Inspector
    var xMin : float;
    var xMax : float;
    var zMin : float;
    var zMax : float;
}

// Theese variables are public to make the code easy-reusable
// You can setup theese variables from Inspector
var speed : float;
var tilt : float;
var boundary : Boundary;

function FixedUpdate () {
     // Get User Input START
     var moveHorizontal : float= Input.GetAxis ("Horizontal");
     var moveVertical : float= Input.GetAxis ("Vertical");
     // Get User Input END

     var movement : Vector3= new Vector3 (moveHorizontal, 0.0f, moveVertical);
    rigidbody.velocity = movement * speed;

    // Limitate movement inside the screen START
    rigidbody.position = new Vector3 
    (
        Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
        0.0f, 
        Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
    );
     // Limitate movement inside the screen END

    // Tilt movement START
    rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    // Tilt movement END
}

2. Hierarchy> select the Space Ship GameObject> Inspector> ‘PlayerController.js’

– Speed
– Tilt

Boundary
– XMin: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change X Position

– XMax: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change X Position

– ZMin: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change Z Position

– ZMax: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change Z Position