Mrshcovington.weebly.com



Game Design BUnit 1 Tutorial Instructions (fixed):The online textbook has many errors that will cause your program to fail to work. I’ve made corrections (in red) to this textbook that will allow you to complete the activity correctly. Open your project and your “Hover Cube” scene. If you don’t have this from Semester 1, you can find my copy on the Message Boards. From the menu bar in Unity, select Edit > Project Settings > Input. You will notice an object called InputManager in the inspector view.Expand the option for Axes, and you will see a host of channels you can assign controls to. You will be assigning controls to the horizontal and vertical channels in the script.Double click on the Handler script to open it, and if they are still there, comment out (i.e. place a “//” at the beginning of) any print messages or the Translate command from the previous unit.Since you want to tell the cube how you want it to move horizontally, you are going to add code into the argument for the x translation, otherwise known as the x-axis! Remember, the values inside the Translate parentheses are the x, y, and z translations.Inside the Update loop, type your statement until it looks exactly like this, character-for-character:18361925888100transform.Translate(speed * Input.GetAxis("Horizontal"));You still have to make an adjustment. When you are playing a game, it is constantly drawing objects on the screen frame by frame, like a movie reel. Since some frames have more to draw, they require more processing power, and so some frames take longer than others. This can make the movement of objects jerky. To fix the problem, you use a subclass of the Time class, called “deltatime”. Delta Time is used to calculate how far a game object would translate during a specific period of time. You’ll make your object’s movement smooth by multiplying it by the time it took to complete the last frame using the * operator for multiplication. Your line of code should now look exactly like this: You will still get an error message if you try to compile this.transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime, 0f, 0f);Save your script and return to Unity.Look again at the Input Manager and the Horizontal axis parameters. The Negative Button, which means moving left of zero on the grid, is assigned to the left arrow key (just called “left”), and the Positive Button, meaning to the right of 0 on the number line is assigned to the right arrow key. This means these the use of these two buttons will feed into your Translate method to move the cube to the left or right.Make sure your Handler script is one of the components of the cube, like you set up in Unit 5. If it's not, select the cube, then click 'Add Component' at the bottom of the Inspector, and select the Handler script.Now run the game in the Scene window, and use the left and right arrow keys to move the cube along its x-axis. You will not be able to run this game because of a compilation error. Continue on to the next step. To make the cube move along its z-axis as well, you can put the same code in the third argument, where the z value goes. You do need to make one modification, though. Instead of “Horizontal,” you need to put in the string “Vertical.” Now, if you are thinking that vertical is up and down, as far as the engine is concerned, it is just the axis perpendicular to, but on the same plane as, the horizontal axis. Your Handler script now looks like this:using System.Collections;using System.Collections.Generic;using UnityEngine;public class Handler : MonoBehaviour { // Use this for initialization void Start () { //print ("Today I made a cube"); } // Update is called once per frame void Update () { //print ("Today I made a cube"); transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, speed * Input.GetAxis("Vertical") * Time.deltaTime); }}Save the script, run the game, and use the four arrow keys to slide the cube around.Maybe the cube is moving a little too slowly for your taste. Let’s speed it up. Go back into the script and create a public variable to store the speed of the cube as a float value. A public variable means it can be accessed by the whole game, not just this script. Go to the line before the start method, and add the following:public float speed = 5;You want to multiply the translation on both axes by speed, so go back to the transform.Translate section and multiply the x and z arguments by speed like this: This makes no change to the script. Please ignore this step. Save the script and run the game. Now your cube moves more quickly.Movement BoundariesLet’s define some Bounds so the cube can only move around on the plane.Open up the Handler script again and near the top, under the “using” calls you’ll add a public class called Bounds like this:[System.Serializable]public class Bounds{ public float xMin, xMax, zMin, zMax;}In the Handler class, just after the speed variable declaration, create an instance of the Bounds class called bounds; note that while the class name and instance name look similar, the class name is capitalized, whereas the instance name is not, which differentiates them:public Bounds bounds;Then, in the update loop, you will add the code that will define the limits of movement range. Let’s look at the code you will add first and then examine how it works. The update section will look like this: void Update(){ transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, speed * Input.GetAxis("Vertical") * Time.deltaTime); transform.position = new Vector3 ( Mathf.Clamp(transform.position.x, bounds.xMin, bounds.xMax), 0.5f, Mathf.Clamp(transform.position.z, bounds.zMin, bounds.zMax) );}Save the script, and jump back into Unity to see how this works.Select the cube and look in the inspector. There should now be a value called Bounds under the Handler script component. Expand this option and you will see places to enter values for the four variables you defined in the script (x min, x Max, z Min, z Max). To keep the cube confined to the plane, you need to set the position values to the edges of the plane. The best way to find these is to move the cube in the scene view to the left edge and note the x value. It should be about -4.4; and the right edge will be 4.4. Move the cube to the top edge and bottom edge of the plane and the z values will be -4.4 and 4.4 respectively. Enter these values in the Bounds fields; it will look like this:37661946760300Save the scene and play the game. Now you can slide the cube around, but it won’t go past the limits of the plane.Part II:Programming ConceptsCoding Combat MechanicsFirst, in Unity, from the GameObject menu, choose Create Empty. This will give us an object that is just a transform—sometimes these are called dummy objects; you don’t need them to be visible, you just want to use them to implement game logic. In this case, the transform will be the unseen gun that your cube is holding.Name the transform “shooter,” and find it in the?hierarchy view. Click and hold the name of the shooter and drag it to the cube (in the same?hierarchy view). It should now be nested under the cube, indicating it is a child object of the cube; this means it will automatically inherit the cube’s transform data, so when the cube moves, the shooter will move with it.Now, select the shooter object in the Hierarchy view, and its transform arrows will appear in the Scene view. Using the axis arrows, move the shooter object in the Scene view at the front edge of the cube along the z-axis. Make sure that the z-axis arrows for both objects are pointing in the same direction.Now you’ll create the projectile as a Rigidbody object, so that it will have physics properties. From the GameObject menu, select 3D Object/Cylinder, and name it “Blast.”Scale the cylinder down to a small, bullet-sized object in relation to the cube.Create a new material (using the Create button in the Project view), set the color to red or orange (in the inspector), and assign the color to the bullet (by dragging the material from the Asset view onto the Blast object in the Scene view).In the Inspector view, add a Rigidbody component by clicking the 'Add Component' button, searching for "Rigidbody" and clicking on the component when it appears in the list below as an option. Once added it should appear in your inspector as a component of the Blast object.You can leave most of the Rigidbody values as they are, but under the constraint options, check the boxes to freeze position and rotation on the x and y axes.Click on 'Add Component' and add the Capsule Collider component. This will allow us to detect when the object collides with something else, which is needed for setting events, such as dropping to the ground if it hits a wall!To more accurately align the collider to the game object, click “Edit Collider” in the capsule collider field, then click and drag the points on the green capsule-shaped mesh which surrounds the cylinder to reshape the collider until it more precisely matches the form of the object.Finally, on the transform component, set the x rotation to 90.Once you have the blast object set up, drag its name from the Hierarchy view into the assets that are in the Project view. This creates a prefab, an object that is saved with all of its specific component data so that you can reuse it easily throughout the game. The icon for a prefab is a little blue cube.Now delete the instance of blast in the scene (by right clicking on the game object in the Hierarchy view and selecting delete) because all of your blasts will be spawned, or created dynamically, by your next script!With your Blast prefab selected in the Project view, click 'Add Component' again and select 'New script'. Name the script “Mover” and click 'Create and add'. It should now be visible in your Assets.Double click on the new script to open it up in Visual Studio.Beneath the class declaration (i.e. on the next line after "public class Mover : MonoBehaviour {") you’ll declare a private variable, meaning you only want to use it in this script, which identifies its Rigidbody object with the variable “rb,” and a public variable called “speed” that holds a float value. The code looks like this: private Rigidbody rb; public float speed;1276066335697This is not in the online text00This is not in the online textThen, in the start method, you will use the variables to calculate the velocity of the Rigidbody object by directing it to transform forward so it will only fire in one direction. The code looks like this:void Start() { rb = GetComponent<Rigidbody>(); rb.velocity = transform.forward * speed; }Save the script and open the Handler script which contains your movement code and will also house the logic for firing the bullet.Open the Handler script again in Visual Studio and declare the public variables you will need. In the Handler (not the Bounds class) class, beneath the public bounds variable, create a GameObject called “shot” which you will use to fire the bullet, a Transform variable that tracks where the shot is coming from that is called “shooter”, and a float called “fireRate” that sets the speed of firing. You also need to declare a private variable called “nextFire” that will define an interval between shots to make firing a little more challenging—this is often called a cool-down interval. Your updated Handler class now looks like this:[System.Serializable]public class Bounds{ public float xMin, xMax, zMin, zMax;} public class Handler : MonoBehaviour { public float speed = 5; public Bounds bounds; public GameObject shot; public Transform shooter; public float fireRate; private float nextFire;Because you are dealing with Rigidbody objects, you are going to set up a second game loop. You already have the start method that runs when the game or level first runs, and the update loop that runs every frame. Now you add a variation on the update logic that is called the FixedUpdate loop that is called every fixed framerate frame. This is done so that the physics simulations can be regulated by a specific framerate to ensure the game runs smoothly and simulations don’t get out of hand—such as bouncing balls building up too much momentum and flying out of the level or a crate spinning at absurd speeds (both of which have happened in games, much to the chagrin of the developers).Still in the Handler script, set up this new loop and use it to contain the conditional logic for firing. The code looks like this:void FixedUpdate() { if (Input.GetButton("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; Instantiate(shot, shooter.position, shooter.rotation); } }Save the script and hop back into Unity. Select cube and look at the inspector. In the script component, there are now places to assign values for shot, shooter, and fireRate.For the shot, you need to assign the bullet, so drag the blast from the asset area onto the box for shot.From the hierarchy view, drag the pointer for shooter, which is a child of the cube, into the field for shooter.FireRate is a numeric value you put in yourself. Feel free to experiment with different numbers, but to start, 0.25 seems to work well. The results should look like this:And remember, you are using the controller slot Fire1 to shoot with. Go to Edit > Project Settings > Input where you defined the movement controls, Fire1 is the third option. Expand it and look at the “Positive Button” field. Go ahead and type in “space” (without the quotation marks) for the space bar. By default, the left mouse button is an alternate button—you can leave this if you like.Destroying the BulletsAnd remember, you are using the controller slot Fire1 to shoot with. Go to Edit > Project Settings > Input where you defined the movement controls, Fire1 is the third option. Expand it and look at the “Positive Button” field. Go ahead and type in “space” (without the quotation marks) for the space bar. By default, the left mouse button is an alternate button—you can leave this if you like.Check ‘Box Collider’ in the Inspector. This makes the box a collider, not an actual shape. If you don’t do this, your Blast bullets will automatically appear on the outside of the Bounding Box, because they can’t appear in the middle of a solid object! Make sure you have the “Is Trigger” box checked.You don’t need to see the Bounding Box’s mesh; it is just in the way, so uncheck the box for “Mesh Renderer” in the Inspector. Now you just see the wire frame edges.Add a new script to the Bounding Box (by clicking on Add Component) and call it “Destroy_Bounding.” This script will say that if a bullet leaves the bounding box, then destroy it. It is a simple request and only requires a simple script.Open the script in Visual Studio (click on the cog to the right of the script name and select ‘Edit Script’ from the pop-up menu) and put in the following under the public class section: public class Destroy_Bounding : MonoBehaviour { void OnTriggerExit(Collider collider) { //Destroy everything that leaves the trigger Destroy(collider.gameObject); }You are Finished! Go ahead and save your script, and see if the “Blast” bullets are destroyed. Final Code for each script. Use this as a reference if you code is giving your compilation errors. Handler Script:using System.Collections;using System.Collections.Generic;using UnityEngine;[System.Serializable]public class Bounds{ public float xMin, xMax, zMin, zMax;} public class Handler : MonoBehaviour { public float speed = 5; public Bounds bounds; public GameObject shot; public Transform shooter; public float fireRate; private float nextFire; // Use this for initialization void Start() { } // Update is called once per frame void Update() { transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, speed * Input.GetAxis("Vertical") * Time.deltaTime); transform.position = new Vector3(Mathf.Clamp(transform.position.x, bounds.xMin, bounds.xMax), 0.5f, Mathf.Clamp(transform.position.z, bounds.zMin, bounds.zMax)); } void FixedUpdate() { if (Input.GetButton("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; Instantiate(shot, shooter.position, shooter.rotation); } } }Mover Script:using System.Collections;using System.Collections.Generic;using UnityEngine;public class Mover : MonoBehaviour { private Rigidbody rb; public float speed;// Use this for initializationvoid Start () { rb = GetComponent<Rigidbody>(); rb.velocity = transform.forward * speed;}// Update is called once per framevoid Update () {}}Destroy_Bounding Script:using System.Collections;using System.Collections.Generic;using UnityEngine;public class Destroy_Bounding : MonoBehaviour { void OnTriggerExit(Collider collider) { //Destroy everything that leaves the trigger Destroy(collider.gameObject); } // Use this for initialization void Start () {}// Update is called once per framevoid Update () {} } ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download