Creating Bullets in Unity3D (vers. 4.2)

Similar documents
Shooting in Unity3D (continued)

Space Invadersesque 2D shooter

Unity Game Development Essentials

Adding in 3D Models and Animations

Learn Unity by Creating a 3D Multi-Level Platformer Game

Experiment 02 Interaction Objects

Unity 3.x. Game Development Essentials. Game development with C# and Javascript PUBLISHING

EVAC-CITY. Index. A starters guide to making a game like EVAC-CITY

Section 39: BobmerMan How-To

Instructions for using Object Collection and Trigger mechanics in Unity

First Steps in Unity3D

PoolKit - For Unity.

Shoot It Game Template - 1. Tornado Bandits Studio Shoot It Game Template - Documentation.

Foreword Thank you for purchasing the Motion Controller!

CMSC 425: Lecture 3 Introduction to Unity

Macquarie University Introductory Unity3D Workshop

Creating a First Person Shooter (FPS) Part 2

Control Systems in Unity

Workshop 4: Digital Media By Daniel Crippa

Spell Casting Motion Pack 8/23/2017

VACUUM MARAUDERS V1.0

TATAKAI TACTICAL BATTLE FX FOR UNITY & UNITY PRO OFFICIAL DOCUMENTATION. latest update: 4/12/2013

COMPASS NAVIGATOR PRO QUICK START GUIDE

3D Top Down Shooter By Jonay Rosales González AKA Don Barks Gheist

Sword & Shield Motion Pack 11/28/2017

Heavy Station Kit base 2

Save System for Realistic FPS Prefab. Copyright Pixel Crushers. All rights reserved. Realistic FPS Prefab Azuline Studios.

The purpose of this document is to outline the structure and tools that come with FPS Control.

Tutorial: Creating maze games

Easy Input For Gear VR Documentation. Table of Contents

Meteor Game for Multimedia Fusion 1.5

Crowd-steering behaviors Using the Fame Crowd Simulation API to manage crowds Exploring ANT-Op to create more goal-directed crowds

The Archery Motion pack requires the following: Motion Controller v2.23 or higher. Mixamo s free Pro Longbow Pack (using Y Bot)

Game Maker Tutorial Creating Maze Games Written by Mark Overmars

By Chris Burton. User Manual v1.60.5

Tutorial: A scrolling shooter

Kismet Interface Overview

GAME:IT Junior Bouncing Ball

Kings! Card Swiping Decision Game Asset

Star Defender. Section 1

C# Tutorial Fighter Jet Shooting Game

G54GAM Lab Session 1

The Beauty and Joy of Computing Lab Exercise 10: Shall we play a game? Objectives. Background (Pre-Lab Reading)

PING. Table of Contents. PING GameMaker Studio Assignment CIS 125G 1. Lane Community College 2015

True bullet 1.03 manual

Building Augmented Reality Spatial Audio Compositions for ios Introduction and Terms Spatial Audio Positioning

Gesture Control FPS Horror/Survivor Game Third Year Project (COMP30040)

SteamVR Unity Plugin Quickstart Guide

Unity Certified Programmer

GameSalad Basics. by J. Matthew Griffis

Overview. The Game Idea

DESIGN A SHOOTING STYLE GAME IN FLASH 8

Step 1 - Setting Up the Scene

Magic Leap Soundfield Audio Plugin user guide for Unity

TEMPLE OF LOCKS V1.0

5.0 Events and Actions

COMPUTING CURRICULUM TOOLKIT

CONCEPTS EXPLAINED CONCEPTS (IN ORDER)

1 Shooting Gallery Guide 2 SETUP. Unzip the ShootingGalleryFiles.zip file to a convenient location.

Installation Instructions

Objectives: Create Sprites Create Sounds Create Objects Create Room Program simple game

For more information on how you can download and purchase Clickteam Fusion 2.5, check out the website

Table of Contents. Creating Your First Project 4. Enhancing Your Slides 8. Adding Interactivity 12. Recording a Software Simulation 19

Annex IV - Stencyl Tutorial

Catch The Kites A Lightweight Android Game

Module 4 Build a Game

PHOTOSHOP PUZZLE EFFECT

Ball Color Switch. Game document and tutorial

Building Spatial Audio Compositions for Smartphones A Guide for Relative and Absolute Locative Audio Apps on ios and Android v 1.2

Easy Input Helper Documentation

Z-Town Design Document

Game Design Comp 150GD. Michael Shah 3/6/15

Procedural Level Generation for a 2D Platformer

Introduction. Modding Kit Feature List

Chief Architect X3 Training Series. Layers and Layer Sets

Beginner s Guide to Game Maker 4.3 Programming. Beginner s Guide to Game Maker 4.3 Programming

Unreal Studio Project Template

Pong Game. Intermediate. LPo v1

No Evidence. What am I Testing? Expected Outcomes Testing Method Actual Outcome Action Required

Figure 9.10 This shows the File Scripts menu, where there is now a new script item called Delete All Empty layers.

..... l ss t h t an an $100,000 of 000 of ann an u n al u al gross r evenu n e

AIM OF THE GAME GLACIER RACE. Glacier Race. Ben Gems: 20. Laura Gems: 13

The Aces High Radio. by Hammer

Scrolling Shooter 1945

Kodu Lesson 7 Game Design The game world Number of players The ultimate goal Game Rules and Objectives Point of View

Getting Started. with Easy Blue Print

The editor was built upon.net, which means you need the.net Framework for it to work. You can download that here:

VR Easy Getting Started V1.3

fautonomy for Unity 1 st Deep Learning AI plugin for Unity

How to Make Games in MakeCode Arcade Created by Isaac Wellish. Last updated on :10:15 PM UTC

Roofing. ROOFING A Beginner Level Tutorial. By fw190a8, 7 July 2006

Texas Hold Em Poker Unity Asset Store Project Multiplayer Version

Object Groups By Kyle Gillen (Last Updated 6/9/16)

Princess & Dragon Version 2

15 TUBE CLEANER: A SIMPLE SHOOTING GAME

Sensible Chuckle SuperTuxKart Concrete Architecture Report

Students: Bar Uliel, Moran Nisan,Sapir Mordoch Supervisors: Yaron Honen,Boaz Sternfeld

Key Abstractions in Game Maker

Slime VISIT FOR THE LATEST UPDATES, FORUMS & MORE ASSETS.

Transcription:

AD41700 Computer Games Prof. Fabian Winkler Fall 2013 Creating Bullets in Unity3D (vers. 4.2) I would like to preface this workshop with Celia Pearce s essay Beyond Shoot Your Friends (download from: http://www.gardensandmachines.com/ad41700/readings_f13/pearce2_pass.pdf) and the idea that shooting at things in computer games can be used for so many more things than to kill, destroy or shoot your friends. This is also the premise of this workshop, to challenge the meaning and use of shooting, specifically in the loaded environment of the First Person Shooter game and to experiment with this game mechanic in more imaginative, nuanced, engaging and meaningful ways. Creating Bullets Using Prefabs We start by creating a floor and a wall in a new scene, like this: In the next step we place a first person controller in the scene, so we can move around

freely (don t forget to delete the main camera after placing the first person controller). If you don t have the Character Controller Package already imported into your project (from previous workshops) import it now by going to: Assets > Import Package > Character Controllers. Creating Custom Prefabs We will use the concept of Prefabs, reusable assets, for creating bullets on the fly. I create a simple cube (which we will use as the projectile/bullet later) and turn it into a prefab: Game Object > Create Other > Cube Attach a rigid body component to the cube. While it is selected in the Hierarchy window got to: Component > Physics > RigidBody I rename the cube game object in the Hierarchy window to bullet and I also create a Prefab called prefabbullet (you can name these things whatever you want): Asset > Create > Prefab The Prefab shows up in the Project window. I just need to drag and drop the bullet game object from the Hierarchy window onto the bullet prefab in the Project window to assign it. Winkler, Scripting, Bullets, Counters and GUI workshop, p. 2

Since all the data about the bullet game object is now in the bullet prefab in the Project window, you can delete the bullet game object in the Hierarchy window. Now, I create a JavaScript which, upon being triggered, creates new instances of the bullet prefab: var prefabbullet : Transform; function Update() if (Input.GetButtonDown("Fire1")) // this is left ctrl. var instancebullet = Instantiate(prefabBullet, transform.position, Quaternion.identity); Here is some more background on the Instantiate function: http://docs.unity3d.com/documentation/scriptreference/object.instantiate.html The trigger for creating new instances of the bullet prefab is the Fire1 button. You can find out about which key this button is mapped to by going to the project settings: Edit > Project Settings > Input expanding the properties of Fire1 in the list in the Inspector gives you information about the assigned keys. It also allows you to change keys associated with certain input types, e.g. for moving around, firing, jumping, etc You can also add additional inputs (key or joystick-based) by increasing the size of the Input Manager s Input Axes (in the Inspector under Axes > Size). By default these new properties are created as jump keys, just open up each of them and give them new Winkler, Scripting, Bullets, Counters and GUI workshop, p. 3

names and change their positive button value to the key you would like to assign to each of them. Back to the createbullet script, I attach it to the first person controller and make sure that the prefab prefabbullet is assigned to the prefabbullet variable in the script (I assign it in the Inspector): drag and drop the bullet prefab from the Project window onto the prefabbullet variable in the Inspector: Now you can already try out the new script and you ll see that cubes are being created in the position of the camera. Because they have no forward pointing force attached to them they simply stay in place and are pushed away by new instances of the prefab. Winkler, Scripting, Bullets, Counters and GUI workshop, p. 4

You also see in the Hierarchy window how all the instances of the prefab bullet are listed as you create them: In order for theses bullets to have a direction in which they are moving, we need to add a forward pointing force to the script: var prefabbullet : Transform; var forwardforce = 1000; function Update() if (Input.GetButtonDown("Fire1")) var instancebullet = Instantiate (prefabbullet, transform.position, Quaternion.identity); instancebullet.rigidbody.addforce(transform.forward * forwardforce); We are ready to try out the script and should see the cubes shooting out forward from the camera position rather than just dropping down. Also the initial angle of the newly created bullets is dependent on the viewing angle of the camera (i.e. looking up and shooting makes the bullets fly up). Here is a short video from the official Unity3D tutorials that also talks about instantiation: http://unity3d.com/learn/tutorials/modules/beginner/scripting/instantiate Of course you can also create your own custom trajectories by playing around with the vector of the AddForce function, like this: Winkler, Scripting, Bullets, Counters and GUI workshop, p. 5

var prefabbullet : Transform; var forwardforce = 1000; var upwardforce = 500; function Update() if (Input.GetButtonDown("Fire1")) var instancebullet = Instantiate (prefabbullet, transform.position, Quaternion.identity); instancebullet.rigidbody.addforce(0, upwardforce, forwardforce); The Unity3D website has a very good primer tutorial in vector math, which you can watch here: http://unity3d.com/learn/tutorials/modules/scripting/lessons/vectormaths-dot-cross-products Detecting Collision between Bullets and Gameobjects I added two more cubes to the previous scene the red one called stand, the turquoise one called top_cube. Both new game objects have rigid body components added to them. The idea is that when one of the bullets is hitting them that they would fall to the floor, like this: Next we would like to detect the collision between the bullet and the red stand. We can approach this in two ways: Winkler, Scripting, Bullets, Counters and GUI workshop, p. 6

1) from the perspective of the red stand i.e. do something whenever something hits the stand. 2) from the perspective of the bullet i.e. do something whenever the bullet hits something. 1) Collision with the stand I can write the the following script ( collstand ) using Unity s built-in OnCollisionEnter function and attach it to the stand: private var numberofhits : int = 0; function OnCollisionEnter(theCollision : Collision) numberofhits++; print("the stand has been hit " + numberofhits + " times"); // You can use this line to figure out which game object // the stand collided with (just uncomment to try out): // print(thecollision.gameobject.name); Now the counter variable numberofhits counts every collision that occurs with the stand (it does not need to be from a bullet, e.g. it could also be from the turquoise box sitting on top of the stand, or the stand hitting the wall behind it). If you uncomment the last line of code, you can figure out which game object specifically the stand collided with: thecollision.gameobject.name Let s trigger a sound this time when we hit the stand. I prepared a sound file called bang.aiff (remember Unity only likes uncompressed sound -.aiff or.wav or ogg/vobis. Import the sound file into your Project window: Asset > New Asset You can leave the 3D sound option checked in the Inspector, this will make the metal bang sound more convincingly coming from the stand when you hit it (i.e. louder when you are closer and quieter when farther away from it). I change the collstand script to include two lines that trigger the audio playback: var mysound : AudioClip; private var numberofhits : int = 0; function OnCollisionEnter(theCollision : Collision) numberofhits++; print("the stand has been hit " + numberofhits + " times"); audio.playoneshot(mysound); // You can use this line to figure out which game object // the stand collided with (just uncomment to try out): // print(thecollision.gameobject.name); Winkler, Scripting, Bullets, Counters and GUI workshop, p. 7

Don t forget to drag and drop the sound asset onto the variable mysound in the Inspector after selecting the stand, so the correct sound is assigned to the script. Finally, also attach an audiosource component to the stand, so the sound can be played in the scene Component > Audio > AudioSource. In the Inspector, choose bang as the Audio Clip and uncheck Play On Awake : 2) Collision with the Bullet This works pretty much the same way as with the stand. We can write another script collbullet and attach it to the prefab in this case to know if the bullet really hit the stand: function OnCollisionEnter(theCollision : Collision) if (thecollision.gameobject.name == stand ) print("i hit the stand!"); Winkler, Scripting, Bullets, Counters and GUI workshop, p. 8

Open up the Console window to see all your text feedback from the interactions with the game objects in your scene: Housecleaning Now that we know how to create game objects dynamically at runtime it is a good idea to think about removing them eventually as well. With the scripting experience you have gained so far you can figure out different events that might remove the cube bullets from your scene (e.g. when they collide with another game object), in the following script ( destroybullets ), I use a timer that automatically removes (destroys) the game objects after a certain amount of time: var timeremaining = 3.0; function Update() timeremaining -= Time.deltaTime; if (timeremaining <= 0.0) Destroy(gameObject); Simply attach this script to the bullet prefab and watch the cubes disappear after 3 seconds. Hit Counter with Onscreen Text Since some of the information in the Console window might be helpful for a player as well, I setup a very simple GUI (on screen text) that displays the number of hits the stand has taken. The Unity Reference Manual has a nice introduction to UnityGUI, an easy to use set of commands that produce GUI controls. The following examples show some of its functionality. For a full overview go to: http://docs.unity3d.com/documentation/components/guiscriptingguide.html Winkler, Scripting, Bullets, Counters and GUI workshop, p. 9

In order to create an onscreen text with the UnityGUI we need to create an empty game object and then attach the script below. GameObject > Create Empty This script, which I titled guiscript initially just writes some text into a semitransparent text box. var hitcounter : int = 0; function OnGUI () // Make a background box with text GUI.Box (Rect (10,10,100,90), "hit counter: " + hitcounter); You can make this GUI appear and disappear by enabling or disabling the empty game object s GUIScript component. This is because the OnGUI() function works very similar to an Update() function in that it is being executed every frame of the game for as long as its script is enabled. You can toggle the guiscript s enable property using the following script that you should also attach to the very same empty game object (called enablegui ): var targetscript : guiscript; function Start() targetscript = GetComponent(guiScript); targetscript.enabled = false; function Update () // If the g button is pressed: if(input.getkeydown(keycode.g)) if(targetscript.enabled == false) targetscript.enabled = true; else targetscript.enabled = false; Winkler, Scripting, Bullets, Counters and GUI workshop, p. 10

Now, pushing the g button on the keyboard toggles the GUI on and off. In general, the syntax for accessing public variables, properties and functions in another script attached to the same game object goes like this: var script : ScriptName; script = GetComponent("ScriptName"); script.dosomething (); See also: http://docs.unity3d.com/documentation/scriptreference/component.getcomponent.ht ml Acessing Variables from Other Scripts Because I would like to update the guiscript s hitcounter variable from within the collstand script (the one attached to the stand game object, see p. 7) I need to add a couple of lines of code to the collstand script, like this: var mysound : AudioClip; //private var numberofhits : int = 0; private var otherscript : guiscript; function Start() otherscript = GameObject.Find("GUI").GetComponent(guiScript); function OnCollisionEnter(theCollision : Collision) audio.playoneshot(mysound); otherscript.hitcounter++; // You can use this line to figure out which game object // the stand collided with (just uncomment to try out): // print(thecollision.gameobject.name); Winkler, Scripting, Bullets, Counters and GUI workshop, p. 11

Now we can easily access the hitcounter variable in the guiscript from within the collstand script. For this purpose, we made use of the GameObject.Find() function which allows you to find game objects by their name (i.e. the name that you give them in a scene) and then help you access their components using the GetComponent function (such as scripts, sound, rigidbodies, renderer/materials, etc.), more documentation about the GameObject.Find() function is here: http://docs.unity3d.com/documentation/scriptreference/gameobject.find.html And this is what the final scene looks like with the GUI counter: Winkler, Scripting, Bullets, Counters and GUI workshop, p. 12