SlideShare a Scribd company logo
1 of 28
Introduction to
Game Development with Unity
By Luca Leone
lucaleone@outlook.com
Il gioco
Let’s see a demo
Let’s get started
• Scarica da GitHub:
https://github.com/GameLabRomaTre/Materiale-lezione-6-Aprile
• Lancia una nuova instanza di Unity3D
• Apri il progetto appena scaricato
Unity3D
Scene: traslazione, rotazione oggetti,
editing della scena di gioco
Hierarchy: gestione
parentela e tag
Project: gestione delle
risorse del progetto
Inspector: modifica
proprietà dell’oggetto
selezionato nella scena
Creazione campo da gioco
• Right click sul pannello Hierarchy
• Creare Empty (position 0, 0, 0) nominalo ‘’Terrain’’
• Creare cube (size 200, 0.2, 200) dentro a ‘’Terrain’’, nominarlo
‘’base’’
• Nel pannello Project creare cartella Materials, e creare un
materiale, nominarlo ‘’TerrainMat’’, assegnare qusto materiale a
‘’base’’
Creazione elementi di gioco, Ostacolo
• Nella cartella Models selezionare ‘’OstacoloDemo2017’’ e trascinarlo
sulla Hierarchy
• Settare la position Y a 0,69
• Click su Add Component, aggiungere un capsule collider con:
• Center: 0 1 0
• Radius: 1,2
• Height: 0,2
• Direction: Y-Axis
• Click su Add Component, aggiungere un Rigidbody con Mass 5
• Creare in Project una cartella chiamata prefabs, trascinare l’oggetto di
scena nella cartella Prefabs al fine di creare un prefab
Creazione elementi di gioco, Flag
• Creare un Empty, nominarlo Flag, settare position Y a 2.52
aggiungere uno Sphere collider, check Trigger, settare Radius a 1,8
• Nella cartella Models selezionare ‘’RingDemo2017’’ e trascinarlo
sulla Hierarchy all’interno di Flag, con rotation Y 45 e scale a 70 70
70
• Assegnare script FlagTrigger
• Trascinare l’oggetto di scena ‘’Flag’’ nella cartella Prefabs al fine di
creare un prefab
• In FlagsSpawnPoints taggare il prefab ‘’Flag’’
Creazione elementi di gioco, Roccia
• Nella cartella Models selezionare ‘’RocciaDemo2017’’ e trascinarlo sulla
Hierarchy
• Settare la position Y a 0,81 e rotation X a -90
• Click su Add Component, aggiungere un capsule collider con:
• Center: 0 0.0018 0.018
• Radius: 0,013
• Height: 0,042
• Direction: Z-Axis
• Trascinare l’oggetto di scena nella cartella Prefabs al fine di creare un
prefab
Create il vostro campo di gioco!
Creazione controlli gioco
La creazione dei controlli di gioco ha una procedura simile a quella dei
prefab fatti precedentemente
• Creare Empty (position 0, 0, 0) nominalo ‘’GameControls’’
• Spostare la camera all’interno di questo.
• Position: -72.5 73 -43.5
• Rotation: 40 60 0
• Projection: orthographic; Size: 9.46
• Creare Empty (position 0, 0, 0) dentro a ‘’ ’GameControls’’, nominarlo
‘’Car (root) msimple’’
• Trascinare all’interno di questo il modello della macchina (position 0, 0,
0.45; Rotation 0, 180, 0)
Gestione fisica in unity
• Aggiungere i seguenti collider a ‘’Car (root) msimple’’:
• Capsule: Center Z: -1,38; Radius: 0,9; Height 6,2; direction Z-Axis
• Capsule: Center: -1,33 -0,62 -1,44; Radius: 0,5; Height 5,3; direction Z-Axis
• Capsule: Center: 1,33 -0,62 -1,44; Radius: 0,5; Height 5,3; direction Z-Axis
• Sphere: check Trigger; Center: 0 -0,7 -3,63; Radius: 0.78
• Aggiungere un Rigidbody a ‘’Car (root) msimple’’
• In Project creare una cartella ‘Source’, dentro questa creare uno
script ‘MSimpleCarSimulation’ e assegnarlo a ‘’Car (root) msimple’’
The Car script
public class CarSimulator : MonoBehaviour
{
public float Speed = 12f;
public float TurnSpeed = 180f;
public Transform[] FrontWheels;
public Transform[] RearWheels;
public int TriggerCount = 0;
public bool engine;
private Rigidbody m_Rigidbody;
private int maxWheelsRotation = 20; //degree
Definizione membri pubblici e privati classe
The Car script
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (IsOnTheGround()) EnableEngine();
else DisableEngine();
MoveCar(Input.GetAxis("Accelerate"), Input.GetAxis("Steer"));
}
Utilizzo del framework unity
Awake
OnEnable
Start
Update
FixedUpdate
Lateupdate
Inizialization FPS
Disable
OnApplicationPause
OnApplicationQuit
Disable
Torna su OnEnable
OnDestroy
Comportamento MonoBehaviour
The Car script
public void MoveCar(float accelValue, float steerDirection)
{
// Create a vector in the direction the car is facing with a magnitude based on the input, speed and the time between
frames.
Vector3 movement = transform.forward * accelValue * Speed * Time.fixedDeltaTime;
// Determine the number of degrees to be turned based on the input, speed and time between
frames.
float turn = steerDirection * TurnSpeed * Time.fixedDeltaTime;
// Make this into a rotation in the y axis.
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
// If the engine is enabled
if (engine)
{
m_Rigidbody.MovePosition(m_Rigidbody.position + movement);
m_Rigidbody.MoveRotation(m_Rigidbody.rotation * turnRotation);
}
// Wheel rotation animation
RotateWheels((accelValue + turn) * Speed, steerDirection * maxWheelsRotation);
}
Movimento e rotazione macchina
The Car script
private void RotateWheels(float rotationSpeed, float turn)
{
foreach (Transform wheel in FrontWheels)
{
wheel.Rotate(new Vector3(rotationSpeed, 0, 0));
wheel.localRotation = Quaternion.Euler(wheel.localRotation.x, wheel.localRotation.y +
turn, wheel.localRotation.z);
}
foreach (Transform wheel in RearWheels)
{
wheel.Rotate(new Vector3(rotationSpeed, 0, 0));
}
}
Animazione ruote
The Car script
// Checks if the car is on the ground to avoid mid-air acceleration
private void OnTriggerEnter(Collider other)
{
TriggerCount++;
}
private void OnTriggerExit(Collider other)
{
TriggerCount--;
}
public bool IsOnTheGround()
{
return TriggerCount != 0;
}
public void EnableEngine()
{
engine = true;
}
public void DisableEngine()
{
engine = false;
}
Gestione engine
Un tocco finale
Creare un nuovo script in Source chiamato ‘’CameraFollow’’ e
assegnarlo alla Camera
public Vector3 Offset;
public Transform vehicle;
private Transform myTrasform;
void Start ()
{
myTrasform = GetComponent<Transform>();
}
void FixedUpdate ()
{
myTrasform.position = vehicle.position + Offset;
}
Un tocco finale
• In Camera:
• Impostare offset a: -72,5 73 -43,5
• Taggare in vehicle ‘’Car (root) msimple’’
• In Car (root) msimple impostare:
• Speed:23
• Turn Speed: 130
• Taggare le ruote
• Taggare GameElement ‘’Player’’
Eppur si muove!
Creazione Game manager
La creazione di un GameManager permette di avere un punto di
riferimento per la gestione della logica di gioco
• Creare Empty (position 0, 0, 0) nominalo ‘’GameManager’’
• Creare uno script ‘’GameManager’’, assegnalo all’oggetto di scena
• Assegnare Tag al gameManager come ‘’GameManager’’
Game manager script
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public TimerView timerView;
public ScoreView scoreView;
public GameObject endgameView;
public SpawnFlag spawner;
string playerTag = "Player";
string thisScenePath = "Scene/testScene";
public float time=300;
bool gameOver=false;
public bool disableUserInput { get; set; }
int playerScore=0;
void Start()
{
spawner.SpawnNextFlag();
}
Definizione membri pubblici e privati classe
Game manager script
void Update ()
{
if(!gameOver)
{
UpdateTimer();
}
else
{
if(Input.GetKey(KeyCode.Return))
ResetGame();
if(Input.GetKey(KeyCode.Q))
Application.Quit();
}
}
void UpdateTimer()
{
time -= Time.deltaTime;
if (time < 0)
EndGame();
else
timerView.UpdateTimer(time);
}
Il metodo Update gestisce il timer e lo stato della partita
Game manager script
public void FlagTaken(string player)
{
playerScore += 1;
if (player == this.playerTag)
scoreView.SetScore(playerScore);
spawner.SpawnNextFlag();
}
void EndGame()
{
gameOver = true;
disableUserInput = true;
Time.timeScale = 0;
endgameView.SetActive(true); // Show a message when you win with the total
points
}
void ResetGame()
{ // Fai un restart della scena
SceneManager.LoadScene(thisScenePath, LoadSceneMode.Single);
}
Il metodo Update gestisce il timer e lo stato della partita
Un tocco finale
• In GameManager:
• Taggare Timer, Score e EndGamePanel contenuti in Canvas
• Taggare ‘’ FlagsSpawnPoints’’ in Spawner
• In ‘’ FlagTrigger’’ rimuovere commento nella linea 13
Contatti
Luca Emanuele Leone
lucaleone@outlook.com
it.linkedin.com/in/lucaleone93/
GameLab
FanPage
Credits
• Code written by: Andrea salvoni, Gaetano Bonofiglio, Luca Leone
• 3D models by: Luca Leone
• Special thanks to Veronica Iovinella

More Related Content

Similar to Lezione 6 aprile GameLab

Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)Davide Cerbo
 
Progetto su iPhone - Seminario di Reti Wireless
Progetto su iPhone - Seminario di Reti WirelessProgetto su iPhone - Seminario di Reti Wireless
Progetto su iPhone - Seminario di Reti WirelessSilvio Daminato
 
Android Widget @ whymca 2011
Android Widget @ whymca 2011Android Widget @ whymca 2011
Android Widget @ whymca 2011Fabio Collini
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacyTommaso Torti
 
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...Dominopoint - Italian Lotus User Group
 
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerQt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerPaolo Sereno
 
Xcode - Just do it
Xcode - Just do itXcode - Just do it
Xcode - Just do itpragmamark
 
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...Danilo Riso
 
Introduzione a WebGL
Introduzione a WebGLIntroduzione a WebGL
Introduzione a WebGLnigerpunk
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceGiuseppe Toto
 
Controllo della telecamera virtuale in software di modellazione in base a pro...
Controllo della telecamera virtuale in software di modellazione in base a pro...Controllo della telecamera virtuale in software di modellazione in base a pro...
Controllo della telecamera virtuale in software di modellazione in base a pro...Mattias Cibien
 
Making iOS UIKit Simulator for MacOS X
Making iOS UIKit Simulator for MacOS XMaking iOS UIKit Simulator for MacOS X
Making iOS UIKit Simulator for MacOS XDaniele Margutti
 
jQuery - 5 | WebMaster & WebDesigner
jQuery - 5 | WebMaster & WebDesignerjQuery - 5 | WebMaster & WebDesigner
jQuery - 5 | WebMaster & WebDesignerMatteo Magni
 

Similar to Lezione 6 aprile GameLab (20)

Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)Non Conventional Android Programming (Italiano)
Non Conventional Android Programming (Italiano)
 
Progetto su iPhone - Seminario di Reti Wireless
Progetto su iPhone - Seminario di Reti WirelessProgetto su iPhone - Seminario di Reti Wireless
Progetto su iPhone - Seminario di Reti Wireless
 
Android Widget @ whymca 2011
Android Widget @ whymca 2011Android Widget @ whymca 2011
Android Widget @ whymca 2011
 
Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacy
 
Gestire i pdf con iOS
Gestire i pdf con iOSGestire i pdf con iOS
Gestire i pdf con iOS
 
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...
Dati, dati, dati! - Sfruttare le potenzialità delle XPages con Google Chart T...
 
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt DesignerQt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
Qt Lezione4 Parte2: creare un custom widget plugin per Qt Designer
 
Xcode - Just do it
Xcode - Just do itXcode - Just do it
Xcode - Just do it
 
#dd12 Applicazioni a tre voci (Android e Domino)
#dd12 Applicazioni a tre voci (Android e Domino)#dd12 Applicazioni a tre voci (Android e Domino)
#dd12 Applicazioni a tre voci (Android e Domino)
 
La Grafica Con Java
La Grafica Con JavaLa Grafica Con Java
La Grafica Con Java
 
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...
SVILUPPO DI VIDEOGIOCHI SU PIATTAFORMA ANDROID: TUTTA LA POTENZA SU DUE DIMEN...
 
Introduzione a WebGL
Introduzione a WebGLIntroduzione a WebGL
Introduzione a WebGL
 
Sencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codiceSencha touch: panoramica e orientamento sul codice
Sencha touch: panoramica e orientamento sul codice
 
XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13XPages Tips & Tricks, #dd13
XPages Tips & Tricks, #dd13
 
m-v-vm @ UgiAlt.Net
m-v-vm @ UgiAlt.Netm-v-vm @ UgiAlt.Net
m-v-vm @ UgiAlt.Net
 
Controllo della telecamera virtuale in software di modellazione in base a pro...
Controllo della telecamera virtuale in software di modellazione in base a pro...Controllo della telecamera virtuale in software di modellazione in base a pro...
Controllo della telecamera virtuale in software di modellazione in base a pro...
 
Making iOS UIKit Simulator for MacOS X
Making iOS UIKit Simulator for MacOS XMaking iOS UIKit Simulator for MacOS X
Making iOS UIKit Simulator for MacOS X
 
WordCamp Catania 2019 PWA e TWA
WordCamp Catania 2019 PWA e TWAWordCamp Catania 2019 PWA e TWA
WordCamp Catania 2019 PWA e TWA
 
jQuery - 5 | WebMaster & WebDesigner
jQuery - 5 | WebMaster & WebDesignerjQuery - 5 | WebMaster & WebDesigner
jQuery - 5 | WebMaster & WebDesigner
 
Graphics Lezione1
Graphics Lezione1Graphics Lezione1
Graphics Lezione1
 

Recently uploaded

Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Associazione Digital Days
 
Programma Biennale Tecnologia 2024 Torino
Programma Biennale Tecnologia 2024 TorinoProgramma Biennale Tecnologia 2024 Torino
Programma Biennale Tecnologia 2024 TorinoQuotidiano Piemontese
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Associazione Digital Days
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Associazione Digital Days
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Associazione Digital Days
 
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Associazione Digital Days
 
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Associazione Digital Days
 
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Associazione Digital Days
 
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Associazione Digital Days
 

Recently uploaded (9)

Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
Mael Chiabrera, Software Developer; Viola Bongini, Digital Experience Designe...
 
Programma Biennale Tecnologia 2024 Torino
Programma Biennale Tecnologia 2024 TorinoProgramma Biennale Tecnologia 2024 Torino
Programma Biennale Tecnologia 2024 Torino
 
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
Alessio Mazzotti, Aaron Brancotti; Writer, Screenwriter, Director, UX, Autore...
 
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
Daniele Lunassi, CEO & Head of Design @Eye Studios – “Creare prodotti e servi...
 
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
Edoardo Di Pietro – “Virtual Influencer vs Umano: Rubiamo il lavoro all’AI”
 
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
Gabriele Mittica, CEO @Corley Cloud – “Come creare un’azienda “nativa in clou...
 
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
Alessandro Nasi, COO @Djungle Studio – “Cosa delegheresti alla copia di te st...
 
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
Luigi Di Carlo, CEO & Founder @Evometrika srl – “Ruolo della computer vision ...
 
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
Federico Bottino, Lead Venture Builder – “Riflessioni sull’Innovazione: La Cu...
 

Lezione 6 aprile GameLab

  • 1. Introduction to Game Development with Unity By Luca Leone lucaleone@outlook.com
  • 4. Let’s get started • Scarica da GitHub: https://github.com/GameLabRomaTre/Materiale-lezione-6-Aprile • Lancia una nuova instanza di Unity3D • Apri il progetto appena scaricato
  • 5. Unity3D Scene: traslazione, rotazione oggetti, editing della scena di gioco Hierarchy: gestione parentela e tag Project: gestione delle risorse del progetto Inspector: modifica proprietà dell’oggetto selezionato nella scena
  • 6. Creazione campo da gioco • Right click sul pannello Hierarchy • Creare Empty (position 0, 0, 0) nominalo ‘’Terrain’’ • Creare cube (size 200, 0.2, 200) dentro a ‘’Terrain’’, nominarlo ‘’base’’ • Nel pannello Project creare cartella Materials, e creare un materiale, nominarlo ‘’TerrainMat’’, assegnare qusto materiale a ‘’base’’
  • 7. Creazione elementi di gioco, Ostacolo • Nella cartella Models selezionare ‘’OstacoloDemo2017’’ e trascinarlo sulla Hierarchy • Settare la position Y a 0,69 • Click su Add Component, aggiungere un capsule collider con: • Center: 0 1 0 • Radius: 1,2 • Height: 0,2 • Direction: Y-Axis • Click su Add Component, aggiungere un Rigidbody con Mass 5 • Creare in Project una cartella chiamata prefabs, trascinare l’oggetto di scena nella cartella Prefabs al fine di creare un prefab
  • 8. Creazione elementi di gioco, Flag • Creare un Empty, nominarlo Flag, settare position Y a 2.52 aggiungere uno Sphere collider, check Trigger, settare Radius a 1,8 • Nella cartella Models selezionare ‘’RingDemo2017’’ e trascinarlo sulla Hierarchy all’interno di Flag, con rotation Y 45 e scale a 70 70 70 • Assegnare script FlagTrigger • Trascinare l’oggetto di scena ‘’Flag’’ nella cartella Prefabs al fine di creare un prefab • In FlagsSpawnPoints taggare il prefab ‘’Flag’’
  • 9. Creazione elementi di gioco, Roccia • Nella cartella Models selezionare ‘’RocciaDemo2017’’ e trascinarlo sulla Hierarchy • Settare la position Y a 0,81 e rotation X a -90 • Click su Add Component, aggiungere un capsule collider con: • Center: 0 0.0018 0.018 • Radius: 0,013 • Height: 0,042 • Direction: Z-Axis • Trascinare l’oggetto di scena nella cartella Prefabs al fine di creare un prefab
  • 10. Create il vostro campo di gioco!
  • 11. Creazione controlli gioco La creazione dei controlli di gioco ha una procedura simile a quella dei prefab fatti precedentemente • Creare Empty (position 0, 0, 0) nominalo ‘’GameControls’’ • Spostare la camera all’interno di questo. • Position: -72.5 73 -43.5 • Rotation: 40 60 0 • Projection: orthographic; Size: 9.46 • Creare Empty (position 0, 0, 0) dentro a ‘’ ’GameControls’’, nominarlo ‘’Car (root) msimple’’ • Trascinare all’interno di questo il modello della macchina (position 0, 0, 0.45; Rotation 0, 180, 0)
  • 12. Gestione fisica in unity • Aggiungere i seguenti collider a ‘’Car (root) msimple’’: • Capsule: Center Z: -1,38; Radius: 0,9; Height 6,2; direction Z-Axis • Capsule: Center: -1,33 -0,62 -1,44; Radius: 0,5; Height 5,3; direction Z-Axis • Capsule: Center: 1,33 -0,62 -1,44; Radius: 0,5; Height 5,3; direction Z-Axis • Sphere: check Trigger; Center: 0 -0,7 -3,63; Radius: 0.78 • Aggiungere un Rigidbody a ‘’Car (root) msimple’’ • In Project creare una cartella ‘Source’, dentro questa creare uno script ‘MSimpleCarSimulation’ e assegnarlo a ‘’Car (root) msimple’’
  • 13. The Car script public class CarSimulator : MonoBehaviour { public float Speed = 12f; public float TurnSpeed = 180f; public Transform[] FrontWheels; public Transform[] RearWheels; public int TriggerCount = 0; public bool engine; private Rigidbody m_Rigidbody; private int maxWheelsRotation = 20; //degree Definizione membri pubblici e privati classe
  • 14. The Car script void Start() { m_Rigidbody = GetComponent<Rigidbody>(); } void FixedUpdate() { if (IsOnTheGround()) EnableEngine(); else DisableEngine(); MoveCar(Input.GetAxis("Accelerate"), Input.GetAxis("Steer")); } Utilizzo del framework unity
  • 16. The Car script public void MoveCar(float accelValue, float steerDirection) { // Create a vector in the direction the car is facing with a magnitude based on the input, speed and the time between frames. Vector3 movement = transform.forward * accelValue * Speed * Time.fixedDeltaTime; // Determine the number of degrees to be turned based on the input, speed and time between frames. float turn = steerDirection * TurnSpeed * Time.fixedDeltaTime; // Make this into a rotation in the y axis. Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f); // If the engine is enabled if (engine) { m_Rigidbody.MovePosition(m_Rigidbody.position + movement); m_Rigidbody.MoveRotation(m_Rigidbody.rotation * turnRotation); } // Wheel rotation animation RotateWheels((accelValue + turn) * Speed, steerDirection * maxWheelsRotation); } Movimento e rotazione macchina
  • 17. The Car script private void RotateWheels(float rotationSpeed, float turn) { foreach (Transform wheel in FrontWheels) { wheel.Rotate(new Vector3(rotationSpeed, 0, 0)); wheel.localRotation = Quaternion.Euler(wheel.localRotation.x, wheel.localRotation.y + turn, wheel.localRotation.z); } foreach (Transform wheel in RearWheels) { wheel.Rotate(new Vector3(rotationSpeed, 0, 0)); } } Animazione ruote
  • 18. The Car script // Checks if the car is on the ground to avoid mid-air acceleration private void OnTriggerEnter(Collider other) { TriggerCount++; } private void OnTriggerExit(Collider other) { TriggerCount--; } public bool IsOnTheGround() { return TriggerCount != 0; } public void EnableEngine() { engine = true; } public void DisableEngine() { engine = false; } Gestione engine
  • 19. Un tocco finale Creare un nuovo script in Source chiamato ‘’CameraFollow’’ e assegnarlo alla Camera public Vector3 Offset; public Transform vehicle; private Transform myTrasform; void Start () { myTrasform = GetComponent<Transform>(); } void FixedUpdate () { myTrasform.position = vehicle.position + Offset; }
  • 20. Un tocco finale • In Camera: • Impostare offset a: -72,5 73 -43,5 • Taggare in vehicle ‘’Car (root) msimple’’ • In Car (root) msimple impostare: • Speed:23 • Turn Speed: 130 • Taggare le ruote • Taggare GameElement ‘’Player’’
  • 22. Creazione Game manager La creazione di un GameManager permette di avere un punto di riferimento per la gestione della logica di gioco • Creare Empty (position 0, 0, 0) nominalo ‘’GameManager’’ • Creare uno script ‘’GameManager’’, assegnalo all’oggetto di scena • Assegnare Tag al gameManager come ‘’GameManager’’
  • 23. Game manager script using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public TimerView timerView; public ScoreView scoreView; public GameObject endgameView; public SpawnFlag spawner; string playerTag = "Player"; string thisScenePath = "Scene/testScene"; public float time=300; bool gameOver=false; public bool disableUserInput { get; set; } int playerScore=0; void Start() { spawner.SpawnNextFlag(); } Definizione membri pubblici e privati classe
  • 24. Game manager script void Update () { if(!gameOver) { UpdateTimer(); } else { if(Input.GetKey(KeyCode.Return)) ResetGame(); if(Input.GetKey(KeyCode.Q)) Application.Quit(); } } void UpdateTimer() { time -= Time.deltaTime; if (time < 0) EndGame(); else timerView.UpdateTimer(time); } Il metodo Update gestisce il timer e lo stato della partita
  • 25. Game manager script public void FlagTaken(string player) { playerScore += 1; if (player == this.playerTag) scoreView.SetScore(playerScore); spawner.SpawnNextFlag(); } void EndGame() { gameOver = true; disableUserInput = true; Time.timeScale = 0; endgameView.SetActive(true); // Show a message when you win with the total points } void ResetGame() { // Fai un restart della scena SceneManager.LoadScene(thisScenePath, LoadSceneMode.Single); } Il metodo Update gestisce il timer e lo stato della partita
  • 26. Un tocco finale • In GameManager: • Taggare Timer, Score e EndGamePanel contenuti in Canvas • Taggare ‘’ FlagsSpawnPoints’’ in Spawner • In ‘’ FlagTrigger’’ rimuovere commento nella linea 13
  • 28. Credits • Code written by: Andrea salvoni, Gaetano Bonofiglio, Luca Leone • 3D models by: Luca Leone • Special thanks to Veronica Iovinella