Unity How to Make Simple Asteroid Ship Movement

Follow below steps to create a moving and jumping player.

  • Create a player sprite/gameobject
  • Add a RigidBody2D component;
  • Set the RigidBody2D gravityScale to 0;

Add this script to your GameObject:

Ship.cs
using UnityEngine;
using System.Collections;
 
public class Ship : MonoBehaviour {
 
	int maxSpeed = 1000;
	int acc = 600;
	int rotateSpeed = 300;
 
	void Update () {
 
		// BUG: cannot slow down when at max speed
		float v = Input.GetAxis ("Vertical");
		if (v != 0) {
			GetComponent<Rigidbody2D> ().AddForce (transform.up * v * Time.deltaTime * acc);
		}
 
		float h = -Input.GetAxis ("Horizontal");
		transform.Rotate(new Vector3(0, 0, h * Time.deltaTime * rotateSpeed));
 
		transform.position = Game.rePositionAfterOffScreen(transform.position);
	}
}

Create a Game script. This has a method to reposition the ship when it goes off screen.

Game.cs
using UnityEngine;
using System.Collections;
 
public class Game : MonoBehaviour {
 
	void Update () {
		if (Input.GetKey ("escape")) {
			Application.Quit();
		}			
	}
 
	public static Vector3 rePositionAfterOffScreen(Vector3 position) {
		Vector3 viewPortPos = Camera.main.WorldToViewportPoint (position);
 
		if (viewPortPos.y > 1) {
			return Camera.main.ViewportToWorldPoint (new Vector3(viewPortPos.x, 0f, viewPortPos.z));
		}
 
		if (viewPortPos.y < 0) {
			return Camera.main.ViewportToWorldPoint (new Vector3(viewPortPos.x, 1f, viewPortPos.z));
		}
 
		if (viewPortPos.x > 1) {
			return Camera.main.ViewportToWorldPoint (new Vector3(0f, viewPortPos.y, viewPortPos.z));
		}
 
		if (viewPortPos.x < 0) {
			return Camera.main.ViewportToWorldPoint (new Vector3(1f, viewPortPos.y, viewPortPos.z));
		}
 
		return position;
	}
}
Navigation
Print/export
Toolbox