Unity3D Tutorial

35
Unity3D Tutorial Unity3D Tutorial First Person Shooter Project

description

Unity3D Tutorial. First Person Shooter Project. FPS Project. First Person Shooter Project 게임 환경 제작 Game Object 와 Material 를 이용한 자체 제작 Asset Store 를 이용한 게임환경 제작 Character Controller 적용 Script 를 이용한 Shooting Rain {indie} 를 이용한 Enemy AI 적용 게임 GUI 구성. Game World 제작 준비. - PowerPoint PPT Presentation

Transcript of Unity3D Tutorial

Page 1: Unity3D Tutorial

Unity3D TutorialUnity3D TutorialUnity3D TutorialUnity3D Tutorial

First Person Shooter Project

Page 2: Unity3D Tutorial

FPS Project

■ First Person Shooter Project 게임 환경 제작

• Game Object 와 Material 를 이용한 자체 제작• Asset Store 를 이용한 게임환경 제작

Character Controller 적용 Script 를 이용한 Shooting Rain {indie} 를 이용한 Enemy AI 적용 게임 GUI 구성

Page 3: Unity3D Tutorial

Game World 제작 준비

■ Game World 제작 File Menu New Project “FPS_Starter” Download RAIN Starter Project 1

• Asset Import Package Custom Package Select RAINStarter.unitypackage

• Open “Starter.unity”

Page 4: Unity3D Tutorial

Material 적용

■ Material 적용 Create New Folder “Materials” in Project View Copy any image in “Materials” Folder Create New Material “Box” in Project View Select “Box” Material

• Drag & Drop Sample Image into “Texture” in Inspector View

Select a Cube in Hierarchy View• Drag & Drop “Box” Material into selected Cube in Inspector View

Page 5: Unity3D Tutorial

Asset Store 에서 Asset 가져오기

■ Asset Store 에서 Asset 가져오기 Select Window Asset Store Select Categories Texture & Materials Select Top Free “Metal Texture18 FREE Substance” Download & Import

Page 6: Unity3D Tutorial

Character Controller

■ Character Controller 사용 1 인칭 컨트롤러 추가 방법

• Import Packages > Character Controllers 메뉴 선택• 프로젝트 뷰에서 First Person Controller 드래그하여 씬뷰에 가져다 놓음 ( 캡슐 생김 )

• Rename “Hero”

Page 7: Unity3D Tutorial

Shooting using C# Script

■ Create Empty Object “Launcher” Drag the Launcher object onto the Main Camera object that

belongs to the FPS Controller in the Hierarchy panel

■ Create Bullets Using Prefabs Create Bullets

• Game Object > Create Other > Sphere “bullet” scale 0.2 Attach a rigid body component to the “bullet”

• Component > Physics > RigidBody Create New folder “Prefabs”

• Create New Prefab “prefabBullet”• drag and drop the bullet game object from the Hierarchy

window onto the bullet prefab in the Project window Delete the bullet game object in the Hierarchy window.

Page 8: Unity3D Tutorial

Shooting using C# Script

Select “Launcher” Object Create C# Script “createBullet”

• Add Component > New script• Open MonoDevelop• “prefabBullet” is assigned to the prefab Bullet variable in

the scriptusing UnityEngine;using System.Collections;

public class createBullet : MonoBehaviour { public Rigidbody prefabBullet; public float bulletForce = 1000.0f; void Update() { if (Input.GetButtonDown("Fire1")) { // 총알 오브젝트 (InstanceBullet) 생성 Rigidbody instanceBullet = Instantiate(prefabBullet, transform.position, transform.rotation) as Rigidbody; instanceBullet.AddForce(transform.forward * bulletForce); // 총알 오브젝트 앞으로 발사하는 힘 추가 Physics.IgnoreCollision ( instanceBullet.collider,transform.root.collider ); // Player 와의 충돌 무시 } }}

Launcher 로부터 총알 (Bullet) 발사

Page 9: Unity3D Tutorial

Make Tagret Objects

Create Empty Object “Target Create Game Object Cube “box”

• Attach a rigid body component to the “box” Create Prefab “Box”

• Select Box in Hierarchy View • Drag & Drop the box in Project View

Duplicate “box” object

총알과의 충돌 오브젝트 (Target) 생성

Page 10: Unity3D Tutorial

Explosion

■ Add Explosion Effect Select perfabBullet Add C# Script “Projectile” & Open MonoDevelop Import Standard Assets Particles Select “explosion” prefab Drag & Drop “Explosion” variable

using UnityEngine;using System.Collections;public class Projectile : MonoBehaviour {

public GameObject explosion;

void OnCollisionEnter( Collision collision) { ContactPoint contact = collision.contacts[0]; // 총알과의 충돌지점 Quaternion rotation = Quaternion.FromToRotation( Vector3.up, contact.normal ); // 충돌지점의 방향 GameObject instantiatedExplosion = Instantiate(

explosion, contact.point, rotation ) as GameObject; // 충돌후 폭파 (instantiateExplosion) 오브젝트 생성 Destroy(gameObject); // 총알 오브젝트 제거 }}

충돌 파티클 생성

Page 11: Unity3D Tutorial

Explosion

■ Destroy explosion prefab Select “explosion” prefab Add C# Script “Explosion” & Open MonoDevelop

using UnityEngine;using System.Collections;

public class Explosion : MonoBehaviour { public float explosionTime = 1.0f; void Start () { // 폭파 파티클 1 초후 제거 Destroy( gameObject, explosionTime ); }}

충돌 파티클 제거

Page 12: Unity3D Tutorial

Add Sound

■ Import Sound File Asset store Catagories Audio Sound FX Weapons Select Top Free Futuristic weapon set Download & Import

■ Shooting Sound Select “prefabBullet” in Project View

• Add Component Audio Audio Source• Select Audio Clip & Check Play On Awake

■ Explosion Sound Select “explosion” prefab in Project View

• Add Component Audio Audio Source• Select Audio Clip & Check Play On Awake

총알 발사 및 폭파 사운드 추가

Page 13: Unity3D Tutorial

Enemy Health

■ Select “Max” Enemy Attach a rigid body component to the “Max”

• Check Freeze Rotation X,Y,Z• Check Gravity

Attach Box Collider component Max 오브젝트에 “ Enemy” tag 달기

■ 총알과의 충돌 감지 : Projectile Script 변경public class Projectile : MonoBehaviour { // 중략 …… public int damage=10; void OnCollisionEnter( Collision collision) {// 중략 …… if(collision.gameObject.tag == "Enemy"){

// 총알과 Enemy 테그와 충돌감지시 “ TakeDamage 함수” 호출 collision.gameObject.SendMessage( "TakeDamage", damage, SendMessageOptions.DontRequireReceiver ); } Destroy(gameObject); // 총알 오브젝트 제거 }}

총알 충돌에 의한 적군 체력치 감소

Page 14: Unity3D Tutorial

Enemy Health

■ Displaying GUI Create Empty “DisplayGUI” & Reset Create GUI Text “EnemyHealthText”

• Making Child: Drag into “Display Text”• Change Transform : X1, Y1• Change GUIText

Pixel Offset X-10, Y-10

• Anchor: upper right

■ Select “Max” Enemy Add C# Script “ApplyDamage” Assign “EnemyhealthText”

using UnityEngine;using System.Collections;

public class ApplyDamage : MonoBehaviour { public int health =50; public GUIText enemyhealthText;

void Start() { enemyhealthText.text =""; } void TakeDamage (int damage) { health -= damage; enemyhealthText.text = "Enemy Health: “ + health.ToString(); if(health <= 0) Destroy(gameObject);}

Page 15: Unity3D Tutorial

Player Health

■ Select Player “Hero” Attach Box Collider component Add C# Script

“PlayerHealthControl”

using UnityEngine;using System.Collections;

public class PlayerHealthControl : MonoBehaviour { public int curHealth = 100; public int maxHealth = 100; public GUIText healthText; public GUIText gameoverText; public int damage=10; void Start() { gameoverText.text=""; } void OnCollisionEnter(Collision hit){ // 플레이어와 Enemy 충돌 감지 if(hit.gameObject.tag == "Enemy"){ curHealth -= 10; } } void Update () { healthText.text = "Health " + curHealth.ToString() + " / " + maxHealth.ToString(); if ( curHealth <= 0 ) { gameoverText.text = "Game Over"; // Destroy( gameObject ); } }}

적군과의 충돌에 의한 플레이어 체력치 감소

Page 16: Unity3D Tutorial

Player Health

■ Displaying GUI Create GUI Text “HealthText”

• Change Transform : X0, Y1• Change GUIText : Pixel Offset X10, Y-10• Anchor: upper left

Create GUI Text “GameOverText”• Change Transform : X0.5, Y0.5• Change GUIText

Anchor middle center Alignment center Font Size 50

■ Select “Hero” & Assign GUI Text

Page 17: Unity3D Tutorial

Game Over & Restart

using UnityEngine;using System.Collections;

public class PlayerHealthControl : MonoBehaviour { public int curHealth = 100; public int maxHealth = 100; public GUIText healthText; public GUIText gameoverText; public int damage=10; private bool gameOver; void Start() { gameoverText.text=""; gameOver = false; } void OnCollisionEnter(Collision hit){ if(hit.gameObject.tag == "Enemy“) curHealth -= 10;

}

void Update () { healthText.text = "Health " + curHealth.ToString() + " / " + maxHealth.ToString(); // ToString() if ( curHealth <= 0 ) { gameoverText.text = "Game Over"; healthText.text = "Press 'R' for Restart"; gameOver = true; if (gameOver) { if (Input.GetKeyDown (KeyCode.R)) { Application.LoadLevel (Application.loadedLevel); } } } }}

Page 19: Unity3D Tutorial

Character Controller

■ Character Controller 사용 3 인칭 컨트롤러 배치 및 동작

• 프로젝트 뷰로부터 3 인칭 컨트롤러를 드래그하여 씬에 배치함

• 씬에 배치하면 자동으로 표면 스냅 기능 동작됨• 플레이버튼을 누르면 3 인칭 컨트롤러 동작함• ASDW 로 이동 , Space 로 점프 , Shift 달리기 , Alt 카메라의 시선을빠르게 움직일 수 있음

캐릭터 변경• 교체할 캐릭터에 Component > Script 메뉴를 통해 Third

Person Camera 와 Third Person Controller 컴포넌트 추가 후 입력에 따른 애니메이션만 설정해주면 됨

Page 20: Unity3D Tutorial

Enemy AI

■ Enemy AI Using Rain {indie}

1. Create it from the RAIN Menu

2. Locate it within the Hierarchy

3. Modify it using the Component or Element within the Inspector.

Page 21: Unity3D Tutorial

Enemy AI

■ Creating AI Create Capsule Game Object “NPC”

1. In the RAIN menu, select Create AI.

2. AI object on your GameObject in the hierarchy.

3. Selecting the AI object on your GameObject in the hierarchy will display the AIRig component in the Inspector.

4. Within the AIRig component, you will find the basic 6 elements, and an additional custom element.

Page 22: Unity3D Tutorial

Enemy AI

■ Creating Waypoints In the RAIN menu, select either Create Waypoint Network or

Create Waypoint Route. “NPCWayPoint”• This will add a Waypoint object in the hierarchy.

Selecting “NPCWayPoint” Waypoint Rig editor component in the Inspector.

Within the Waypoint Rig component:• You add waypoints.• Modify waypoint vector position.• Edit the color.• Drop waypoints• Edit their radius.

Page 23: Unity3D Tutorial

Enemy AI

■ Adding Waypoints Click the Add (Ctrl W) button in the Waypoint rig. This creates a waypoint at the center of your camera and

attempts to get it close to the ground. select Drop To Surface.

Page 24: Unity3D Tutorial

Enemy AI

■ Creating a Navigation Mesh1. In the RAIN menu, select Create Navigation Mesh.

2.This will add a Navigation Mesh object in the hierarchy.

3. Nav Mesh Rig in the Inspector.

4. Within the Nav Mesh Rig component:• Adjust Navigation Mesh properties as needed such as

Size and Mesh Color for starters. (“Plane” 과 같은 크기로 설정 )

5. Click Generate Navigation Mesh to create.

Navigation Mesh help with movement across small or large areas quickly while avoiding static obstacles.

Page 25: Unity3D Tutorial

Enemy AI

■ Creating Behavior Open the Behavior Tree Editor by selecting from the menu

RAIN » Behavior Tree Editor. You can also access a shortcut from the AI Mind.

Create a new behavior tree by selecting it from the drop down. This will create a basic tree with a sequencer container in it. “NPCBehavior”

Page 26: Unity3D Tutorial

Enemy AI

Select root & Right click Create Actions Choose Patrol Waypoints Set the property of Patrol Route

• Name “NPCPatrol” , Waypoint Route “NPCWaypoint”• Loop Type “Loop”• Move Target Variable “nextStop”

Page 27: Unity3D Tutorial

Enemy AI

Add Action move • Move Target “nextStop”• Move speed “2”

Add Action animate : Animation state “walk”

Assign Behavior Tree Asset “NPCBehavior”

Basic Object Rigging in RAIN for Unity

Page 28: Unity3D Tutorial

Reference

■ Reference FPS Tutorial

• http://kss2.sd23.bc.ca/chalmers/videoGame12/fps/fps.html Creating Bullet

• http://www.cla.purdue.edu/vpa/etb/resources/tech_workshops.html

Brick Shooter• https://unity3d.com/learn/tutorials/modules/beginner/physi

cs/assignments/brick-shooter Enemy AI

• http://rivaltheory.com/community/tutorials/ EVAC-CITY Video Game Development 11 2013/2014

Page 29: Unity3D Tutorial

First Person Shooter

■ FPS Tutorial Part 1 Introduces fundamental game programming concepts

and gives tips on how to think like a games programmer. Part 2 Details how to implement switchable weapons, combat

logic and some visual tweaks Part 3 Implements the enemy AI, waypoint navigation, audio

effects and an in-game GUI. FPS Tutorial Assets

Page 30: Unity3D Tutorial

First Person Shooter

■ Project Setting copy “FPS_Tutorial.zip” file onto your computer uncompress the FPS_Tutorial Start Unity File OPEN PROJECT

• browse to the folder and choose select Folder

Page 31: Unity3D Tutorial

Unity Project

■ Unity Project Project: Roll-a-Ball Difficulty: Beginner

• In your first foray into Unity development, create a simple rolling ball game that teaches you many of the principles of working with Game Objects, Components, Prefabs, Physics and Scripting.

Project: Space Shooter Difficulty: Beginner• Expand your knowledge and experience of working with Unity by

creating a simple top down arcade style shooter. Using basic assets provided by Unity Technologies, built-in components and writing simple custom code, understand how to work with imported Mesh Models, Audio, Textures and Materials while practicing more complicated Scripting principles.

Project: Stealth Difficulty: Beginner• Create a fully functioning level of a third person stealth game, learn

about player characters, enemies, game logic & management systems.

Page 33: Unity3D Tutorial

Unity Project : Stealth

■ Chapter 3: Interactions 301. Camera Movement 302. The Key 303. Single Doors 304. Double Doors 305. The Lift

■ Chapter 4: Enemy 401. Enemy Setup 402. Enemy Animator Controller 403. Enemy Sight 404. Animator Setup 405. Enemy Animation 406. Enemy Shooting 407. Enemy AI 408. Stretch Goals

Page 34: Unity3D Tutorial

Download Asset

■ Stealth Project Download Asset

Page 35: Unity3D Tutorial

Download Asset

■ Stealth Project : Import Package