c# top down space ship code example

Example: c# top down space ship

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpaceShipMovement : MonoBehaviour
{
    public float moveSpeed = 100f; //how fast the ship moves
    public float rotate_speed = 2; //how fast the ship rotates

    public Rigidbody2D rb; //ships rigidbody 2d

    // Update is called once per frame
    void Update()
    {
    	//rotates ship to the right
        if (Input.GetKey("d") ||  Input.GetKey("right"))
        {
        	//rotates z axis for 2d
            transform.Rotate(0, 0, -rotate_speed);
        }
        
		//rotates ship to the left
        if (Input.GetKey("a") || Input.GetKey("left"))
        {
        	//rotates z axis for 2d
            transform.Rotate(0, 0, rotate_speed);
        }

    }

    private void FixedUpdate()
    {
    	//arrow key up and w
        if (Input.GetKey("up") || Input.GetKey("w"))
        {
            rb.AddForce(transform.up * moveSpeed);
            //when going forward rotates faster
            rotate_speed = 2;
        }

    	//arrow key down and s
        if (Input.GetKey("down") || Input.GetKey("s"))
        {
        	//ship travles x3 slower than movespeed when going backwards
            rb.AddForce(transform.up * -(moveSpeed/3));
            //when going backwards rotates slower
            rotate_speed = 1;
        }
    }
}

Tags:

Misc Example