Easily make a space shooter!
With this tutorial, you can make a space shooter game by adding a triangle object that will rotate around a planet, which is a circle. The space shooter is one of the most famous game genres, it was in the early days of computer gaming when games like Space Invaders were relevant to
In this video, I will teach you how to make a space shooter in Unity. It is a sequel to the previous tutorial, but it includes some additional parts, like how to add a bullet shooting feature and how to make a better movement for the rotating object. To make a space shooter, you need to create a bullet object that will also be a triangle, but will be smaller. Here is a quick guide explained through the images that occur in this tutorial:
Script Explanation
You should set its color to white in order to make it clearly visible. But that is not sufficient! You also need a spawn object, and the triangle bullet should have a 2D rigidbody. Make sure to make a prefab of this object. Now you should go back to the C# script: Add a reference to the game object – call it arrowObject. The code for this project is plain and simple, you just need a few lines of code, as explained in the pivot point tutorial:
public float rotationSpeed; InputSystem input; public Transform spawnObject; public GameObject arrowObject; public float shootSpeed; void Awake() { input = new InputSystem(); input.Click.Touch.performed += OnShoot; } private void OnEnable() { input.Enable(); input.Click.Touch.performed += OnShoot; } private void OnDisable() { input.Disable(); input.Click.Touch.performed -= OnShoot; } // Update is called once per frame void Update() { //this rotates the shape around Z-axis transform.Rotate(0, 0, rotationSpeed); } void OnShoot(InputAction.CallbackContext ctx) { if (ctx.performed) { GameObject arrow = Instantiate(arrowObject, spawnObject.position, spawnObject.transform.rotation); Rigidbody2D rb2d = arrow.GetComponent<Rigidbody2D>(); rb2d.AddForce(spawnObject.rotation * Physics.gravity * shootSpeed, ForceMode2D.Force); } }
Add a public transform spawnObject and the last thing you need to have is a shooting speed, which is a float. Drag the prefab and add the shooting speed. As you can see, the prefab does not spawn well. It does not have the required gravity direction. To fix that, go to script and add Physics.gravity to the spawnObject.forward and change force mode to force. This will apply gravity to different rotations of the triangle. The other requirement is transform.Rotate(), which goes into void Update(). GameObject arrow is a definition that ensures that any part of the script can only read it inside ctx.performed. AddForce is the last part of the script that requires Physics.gravity to make sure that the bullets will be spawned at different rotation angles.
No responses yet