{"id":1016,"date":"2015-01-04T16:36:04","date_gmt":"2015-01-04T16:36:04","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=1016"},"modified":"2015-08-10T07:15:31","modified_gmt":"2015-08-10T07:15:31","slug":"unity3d-2d-space-shooter-with-efficiency-calculation","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/codeproject\/unity3d-2d-space-shooter-with-efficiency-calculation\/","title":{"rendered":"How to build a 2D Space shooter with efficiency calculation in Unity3D"},"content":{"rendered":"<p>In this blog post I&#8217;m going to show you how to build a 2D Space shooter with efficiency calculation in Unity3D.<\/p>\n<p>I followed these two blog posts: <a href=\"http:\/\/blog.lessmilk.com\/unity-spaceshooter-1\/\">post #1<\/a> and <a href=\"http:\/\/blog.lessmilk.com\/unity-spaceshooter-2\/\">post #2<\/a>, and updated it for the use with Unity 4.5 and added the counters for number of bullets fired and number of rocks generated and showed the precision efficiency.<\/p>\n<p>You can <a href=\"http:\/\/nikola-breznjak.com\/_testings\/Unity\/Shooter\/\">try my version<\/a>, or you can <a href=\"https:\/\/github.com\/Hitman666\/SpaceShooterUnity3D.git\">download the project<\/a> on GitHub. Following are the steps on how to make it your self:<\/p>\n<ol>\n<ol>\n<li>Start a new <strong>2D<\/strong> project in Unity3D<\/li>\n<li>Create folders <strong>Scripts<\/strong>, <strong>Scenes<\/strong>, <strong>Prefabs<\/strong>, <strong>Textures<\/strong><\/li>\n<li>Put all the texture assets to Textures folder<\/li>\n<li>Save the (ctrl +s) scene to Scenes folder with some name<\/li>\n<li>Drag background to Hierarchy<\/li>\n<li>Drag ship to Hierarchy\n<ol>\n<li>set\u00a0<strong>y<\/strong>\u00a0to -4<\/li>\n<li>add <strong>Rigidbody2D<\/strong><\/li>\n<li>check\u00a0<strong>IsKinematic<\/strong>\u00a0(the gravity doesn&#8217;t affect it)<\/li>\n<\/ol>\n<\/li>\n<li>Add script to ship:\n<pre class=\"lang:default decode:true\">#pragma strict\r\n\/\/ A variable that will contain our bullet prefab\r\npublic var bullet : GameObject;\r\npublic var brzina: int;\r\nvar score : int;\r\n\r\nfunction Start(){\r\n    \tscore = 0;\r\n}\r\n\r\nfunction Update() {  \r\n    \/\/ Move the spaceship horizontally  \r\n    rigidbody2D.velocity.x = Input.GetAxis(\"Horizontal\") * 10;\r\n    rigidbody2D.velocity.y = Input.GetAxis(\"Vertical\") * 10;\r\n\r\n\t\/\/add support for mobile phone tilting\r\n\ttransform.Translate(Input.acceleration.x*Time.deltaTime*20, 0, 0);\r\n    \r\n    if (Input.GetKeyDown(\"space\") || Input.GetMouseButtonDown(0)) {   \r\n    \tInstantiate(bullet, transform.position, Quaternion.identity);\r\n    }    \r\n}<\/pre>\n<\/li>\n<li>Add bullet to Hierarchy\n<ol>\n<li>add Physics2D -&gt; Rigidbody 2D<\/li>\n<li>add script:\n<pre class=\"lang:default decode:true\">public var speed : int = 6;\r\n\r\n\/\/ Gets called once when the bullet is created\r\nfunction Start () {  \r\n    \/\/ Set the Y velocity to make the bullet move upward\r\n    rigidbody2D.velocity.y = speed;\r\n}\r\n\r\n\/\/ Gets called when the object goes out of the screen\r\nfunction OnBecameInvisible() {  \r\n    \/\/ Destroy the bullet \r\n    Destroy(gameObject);\r\n}<\/pre>\n<\/li>\n<li>add bullet to <strong>Prefabs<\/strong> folder and delete it from the Hierarchy<\/li>\n<li>drag the bullet from Prefabs folder to the bullet variable in Inspector when the spaceship is selected<\/li>\n<\/ol>\n<\/li>\n<li>Add an enemy (from Textures) to the Hierarchy\n<ol>\n<li>add Rigidbody 2D<\/li>\n<li>set IsKinematic<\/li>\n<li>add script:\n<pre class=\"lang:default decode:true\">\/\/ Public variable that contains the speed of the enemy\r\npublic var speed : int = -5;\r\n\r\n\/\/ Function called when the enemy is created\r\nfunction Start () {  \r\n    \/\/ Add a vertical speed to the enemy\r\n    rigidbody2D.velocity.y = speed;\r\n\r\n    \/\/ Make the enemy rotate on itself\r\n    rigidbody2D.angularVelocity = Random.Range(-200, 200);\r\n\r\n    \/\/ Destroy the enemy in 3 seconds,\r\n    \/\/ when it is no longer visible on the screen\r\n    Destroy(gameObject, 3);\r\n}\r\n\r\nfunction OnTriggerEnter2D(obj : Collider2D) {  \r\n    var name = obj.gameObject.name;\r\n\r\n    \/\/ If it collided with a bullet\r\n    if (name == \"bullet(Clone)\") {\r\n        \/\/ And destroy the bullet\r\n        Destroy(obj.gameObject);\r\n        \r\n        handleDestroy(gameObject);\r\n    }\r\n\r\n    \/\/ If it collided with the spaceship\r\n    if (name == \"spaceship\") {\r\n        handleDestroy(gameObject);\r\n    }\r\n}\r\n\r\nfunction handleDestroy(gameObject: GameObject){\r\n\tgameObject.Find(\"ScoreText\").SendMessage(\"Hit\");\r\n    Destroy(gameObject);\r\n}<\/pre>\n<\/li>\n<li>Add enemy from Hierarchy to Prefabs folder and delete it from Hierarchy<\/li>\n<\/ol>\n<\/li>\n<li><span style=\"line-height: 1.5;\">Add spawn object to Hierarchy<\/span>\n<ol>\n<li>position it above the background<\/li>\n<li>add script:<\/li>\n<\/ol>\n<ol>\n<li>\n<pre class=\"lang:default decode:true\">public var enemy : GameObject;\r\n\r\n\/\/ Variable to know how fast we should create new enemies\r\npublic var spawnTime : float = 1.3;\r\n\r\nfunction Start() {  \r\n    \/\/ Call the 'addEnemy' function every 'spawnTime' seconds\r\n    InvokeRepeating(\"addEnemy\", spawnTime, spawnTime);\r\n}\r\n\r\n\/\/ New function to spawn an enemy\r\nfunction addEnemy() {  \r\n    \/\/ Variables to store the X position of the spawn object\r\n    \/\/ See image below\r\n    var x1 = transform.position.x - renderer.bounds.size.x\/2;\r\n    var x2 = transform.position.x + renderer.bounds.size.x\/2;\r\n\r\n    \/\/ Randomly pick a point within the spawn object\r\n    var spawnPoint = new Vector2(Random.Range(x1, x2), transform.position.y);\r\n\r\n    \/\/ Create an enemy at the 'spawnPoint' position\r\n    Instantiate(enemy, spawnPoint, Quaternion.identity);\r\n}<\/pre>\n<\/li>\n<li><span style=\"line-height: 1.5;\">drag enemy prefab to spawn object<\/span><\/li>\n<\/ol>\n<\/li>\n<li>For the spaceship, the enemy prefab, and the bullet prefab do the following\n<ol>\n<li>add Component -&gt; Physics 2D -&gt; Box Collider 2D<\/li>\n<li>for enemy Box Collider 2D check IsTrigger and this will give you the\u00a0OnTriggerEnter2D function<\/li>\n<\/ol>\n<\/li>\n<li>Create -&gt; UI -&gt; Text (name it <em>ScoreText<\/em>)\n<ol>\n<li>Canvas -&gt; RenederMode -&gt; World space, no camera<\/li>\n<li>Rect transform &#8211; 450&#215;340 (WxH)<\/li>\n<li>Add -&gt; Script -&gt; <i><i>ScoreScript.js:<br \/>\n<\/i><\/i><\/p>\n<pre class=\"lang:default decode:true\">import UnityEngine.UI.Text;\r\n\r\nvar Counter : int;\r\nvar text : UnityEngine.UI.Text;\r\n\r\nfunction Start () {\r\n\ttext = GetComponent(UnityEngine.UI.Text);\r\n\tCounter = 0;\r\n}\r\n\r\nfunction Update () {    \r\n     text.text = \"Kills: \"+Counter;\r\n}   \r\n         \r\nfunction Hit () {            \r\n    Counter++;\r\n}<\/pre>\n<\/li>\n<\/ol>\n<\/li>\n<li>Create -&gt; UI -&gt; Text (name it\u00a0<em>RocksText<\/em>)\n<ol>\n<li>Add -&gt; Script -&gt;\u00a0<i>RocksScript.js:<br \/>\n<\/i><\/p>\n<pre class=\"lang:default decode:true\">import UnityEngine.UI.Text;\r\n\r\nvar Counter : int;\r\nprivate var text : UnityEngine.UI.Text;\r\n\r\nfunction Start () {\r\n\ttext = GetComponent(UnityEngine.UI.Text);\r\n\tCounter = 0;\r\n}\r\n\r\nfunction Update () {    \r\n     text.text = \"Rocks: \"+Counter;\r\n}   \r\n         \r\nfunction RockAdd () {            \r\n    Counter++;\r\n}<\/pre>\n<\/li>\n<\/ol>\n<\/li>\n<li>Create -&gt; UI -&gt; Text (name it\u00a0<em>EffText<\/em>)\n<ol>\n<li>Add -&gt; Script -&gt; EffScript.js:\n<pre class=\"lang:default decode:true\">import UnityEngine.UI.Text;\r\n\r\nprivate var Kills : int;\r\nprivate var Rocks : int;\r\nprivate var Eff : float;\r\nprivate var text : UnityEngine.UI.Text;\r\n\r\nfunction Start () {\r\n\ttext = GetComponent(UnityEngine.UI.Text);\r\n\tEff = 0;\r\n\tKills = 0;\r\n\tRocks = 0;\r\n}\r\n\r\nfunction Update () {    \r\n     Kills = gameObject.Find(\"ScoreText\").GetComponent(ScoreScript).Counter;\r\n     Rocks = gameObject.Find(\"RocksText\").GetComponent(RocksScript).Counter;\r\n          \r\n     if (Kills == 0 || Rocks == 0)\r\n     \tEff = 0;\r\n     else\r\n     \tEff = Kills * 1.0f \/ Rocks * 100;\r\n     \t\r\n     text.text = \"Eff: \" + Eff.ToString(\"F0\") + \"%\";\r\n}<\/pre>\n<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>In this blog post I&#8217;m going to show you how to build a 2D Space shooter with efficiency calculation in Unity3D. I followed these two blog posts: post&hellip;<\/p>\n","protected":false},"author":1,"featured_media":1064,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8,41],"tags":[],"class_list":["post-1016","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-codeproject","category-unity3d"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1016","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/comments?post=1016"}],"version-history":[{"count":10,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1016\/revisions"}],"predecessor-version":[{"id":2046,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/1016\/revisions\/2046"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/1064"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=1016"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=1016"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=1016"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}