SlideShare a Scribd company logo
1 of 23
Download to read offline
libGDX: 
Implemen.ng 
a 
Simple 
Game 
Jussi 
Pohjolainen 
Tampere 
University 
of 
Applied 
Sciences
Starter 
Class: 
Desktop 
public class Main { 
public static void main(String[] args) { 
LwjglApplicationConfiguration config = new 
LwjglApplicationConfiguration(); 
config.title = "Gorba's Revenge"; 
config.width = 800; 
config.height = 480; 
new LwjglApplication(new MyGame(), config); 
} 
} 
// In Android, the resolution is set by operating system!
public class MyGame implements ApplicationListener { 
// Method called once when the application is created. 
public void create () { } 
// Method called by the game loop from the application 
// every time rendering should be performed. Game logic 
// updates are usually also performed in this method. 
public void render () { } 
// This method is called every time the game screen is re-sized 
// and the game is not in the paused state. It is also called once 
// just after the create() method. 
// The parameters are the new width and height the screen has been resized to in pixels. 
public void resize (int width, int height) { } 
// On Android this method is called when the Home button is 
// pressed or an incoming call is received. On desktop this is called 
// just before dispose() when exiting the application. 
// A good place to save the game state. 
public void pause () { } 
// This method is only called on Android, when the application 
// resumes from a paused state. 
public void resume () { } 
// Called when the application is destroyed. It is preceded by a call to pause(). 
public void dispose () { } 
}
Assets 
• Drag 
sounds, 
images 
to 
android/assets 
folder 
– Desktop 
app 
has 
a 
link 
to 
that 
folder
Asset 
loading 
public class MyGame implements ApplicationListener { 
private Texture gorbaImage; 
private Sound soundEffect; 
private Music backgroundMusic; 
@Override 
public void create() { 
// gorba.png uploaded to GPU and is ready to be used by OpenGL. Image format 
// must be .jpg, .png, .bmp 
gorbaImage = new Texture(Gdx.files.internal(”gorba.png")); 
// Stored in RAM 
soundEffect = Gdx.audio.newSound(Gdx.files.internal("beep.wav")); 
// Streamed from wherever it’s stored 
backgroundMusic = Gdx.audio.newMusic(Gdx.files.internal("ussranthem.mp3")); 
// start the playback of the background music immediately 
rainMusic.setLooping(true); 
rainMusic.play(); 
} 
public void dispose() { 
// Good practice to dispose (clean) assets 
gorbaImage.dispose(); 
soundEffect.dispose(); 
backgroundMusic.dispose(); 
}
Rendering: 
Camera 
• Camera 
is 
like 
“virtual 
window 
into 
our 
world” 
– What 
part 
of 
the 
“world” 
is 
visible? 
• Camera 
– OrthographicCamera 
• When 
the 
human 
eye 
looks 
at 
a 
scene, 
objects 
in 
the 
distance 
appear 
smaller 
than 
objects 
close 
by. 
Orthographic 
projec.on 
ignores 
this 
effect 
– PerspectiveCamera 
• Closer 
objects 
appear 
bigger 
in 
Perspec.veCamera
Using 
Camera 
public class SimpleGame extends ApplicationAdapter { 
private OrthographicCamera camera; 
@Override 
public void create() { 
camera = new OrthographicCamera(); 
// Sets this camera to an orthographic projection, 
// centered at (viewportWidth/2, viewportHeight/2), 
// with the y-axis pointing up or down. 
// true => y points down, false => y points up 
camera.setToOrtho(false, 800, 480);
Word 
about 
OpenGL 
• OpenGL 
(Open 
Graphics 
Library) 
is 
a 
cross-­‐language, 
mul.-­‐plaRorm 
applica.on 
programming 
interface 
(API) 
for 
rendering 
2D 
and 
3D 
vector 
graphics. 
• The 
API 
is 
typically 
used 
to 
interact 
with 
a 
graphics 
processing 
unit 
(GPU), 
to 
achieve 
hardware-­‐ 
accelerated 
rendering. 
• Widely 
used 
in 
CAD, 
virtual 
reality, 
scien.fic 
visualiza.on, 
informa.on 
visualiza.on, 
flight 
simula.on, 
and 
video 
games. 
• libGDX 
uses 
OpenGL 
ES 
and 
has 
interface 
also 
for 
direct 
access 
for 
OpenGL
Texture 
Mapping 
• A 
Texture 
wraps 
a 
standard 
OpenGL 
ES 
texture. 
– A 
texture 
is 
an 
OpenGL 
Object 
that 
contains 
one 
or 
more 
images 
that 
all 
have 
the 
same 
image 
format. 
• Image 
loaded 
into 
the 
GPU’s 
memory 
in 
raw 
format 
• Texture 
mapping 
is 
process 
of 
working 
out 
where 
in 
space 
the 
texture 
will 
be 
applied 
– “To 
s.ck 
a 
poster 
on 
a 
wall, 
one 
needs 
to 
figure 
out 
where 
on 
the 
wall 
he 
will 
be 
gluing 
the 
corners 
of 
the 
paper” 
– Space 
ó 
Wall 
– Mesh 
(Rectangle) 
ó 
Paper 
– Image 
on 
paper 
ó 
Texture
SpriteBatch 
• SpriteBatch 
class 
takes 
care 
of 
texture 
mapping 
• Convenience 
class 
which 
makes 
drawing 
onto 
the 
screen 
easy
public class SimpleGame extends ApplicationAdapter { 
private Texture gorbaImage; 
private OrthographicCamera camera; 
private SpriteBatch batch; 
@Override 
public void create() { 
camera = new OrthographicCamera(); 
batch = new SpriteBatch(); 
// Sets this camera to an orthographic projection, centered at (viewportWidth/2, viewportHeight/2), 
// with the y-axis pointing up or down. true => y points down, false => y points up 
camera.setToOrtho(false, 800, 480); 
gorbaImage = new Texture(Gdx.files.internal("littlegorba.png")); 
} 
@Override 
public void render() { 
// Let's use the coordinate system specified by the camera 
batch.setProjectionMatrix(camera.combined); 
// SpriteBatch is ready for commands 
batch.begin(); 
// Draw a texture to x = 100, y = 100 
batch.draw(gorbaImage, 100, 100); 
batch.draw(gorbaImage, 140, 100); 
batch.draw(gorbaImage, 180, 100); 
batch.draw(gorbaImage, 220, 100); 
// No commands anymore, proceed to process the batch of commands 
// received 
batch.end(); 
} 
}
Clear 
Screen 
@Override 
public void render() { 
// Direct OpenGL call 
// float red [0,1] 
// green 
// blue 
// alpha 
// https://www.opengl.org/sdk/docs/man/html/glClearColor.xhtml 
Gdx.gl.glClearColor(0, 0, 0.2f, 1); 
// Clear the screen with the color chosen 
// http://www.opengl.org/sdk/docs/man/html/glClear.xhtml 
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 
// SpriteBatch is ready for commands 
batch.begin(); 
// Draw a texture to x = 100, y = 100 
batch.draw(gorbaImage, 100, 100); 
batch.draw(gorbaImage, 140, 100); 
batch.draw(gorbaImage, 180, 100); 
batch.draw(gorbaImage, 220, 100); 
// No commands anymore, proceed to process the batch of commands 
// received 
batch.end(); 
}
Gdx.input 
• Ge]ng 
input 
from 
user 
is 
very 
easy 
• Touch 
– Gdx.input.isTouched() 
– Gdx.input.getX() 
– Gdx.input.getY() 
• Accelerometer 
– Gdx.input.getAccelerometerX() 
– Gdx.input.getAccelerometerY() 
– Gdx.input.getAccelerometerZ()
About 
Resolu.on 
• Game 
can 
be 
cross-­‐plaRorm, 
what 
is 
the 
resolu.on? 
• We 
have 
two 
resolu.ons 
– The 
real 
resolu.on 
– The 
world 
resolu.on 
• Mapping 
must 
be 
done 
between 
these 
two!
Real 
resolu.on 
0,0 
World 
resolu.on 
0,480 
Real 
resolu.on 
0,480 
World 
resolu.on 
0,0 
Window 
resolu.on 
800 
x 
480 
World 
resolu.on 
set 
to 
800 
x 
480
Real 
resolu.on 
0,0 
World 
resolu.on 
0,480 
Real 
resolu.on 
0,384 
World 
resolu.on 
0,0 
Window 
width 
640 
x 
384 
World 
resolu.on 
set 
to 
800 
x 
480
Conversion 
@Override 
public void render() { 
if(Gdx.input.isTouched()) { 
int realX = Gdx.input.getX(); 
int realY = Gdx.input.getY(); 
// Encapsulated 3D Vector, only 2D is used 
// Vectors can be used for represent a direction and position 
// Bad practice to instantiate every render – call! 
Vector3 touchPos = new Vector3(realX, realY, 0); 
// Function to translate a point given in screen coordinates to world space. 
camera.unproject(touchPos); 
Gdx.app.setLogLevel(Logger.DEBUG); 
Gdx.app.debug("MyGame", "real X = " + realX); 
Gdx.app.debug("MyGame", "real Y = " + realY); 
Gdx.app.debug("MyGame", "world X = " + touchPos.x); 
Gdx.app.debug("MyGame", "world Y = " + touchPos.y); 
} 
}
Collision 
• Simple 
collision 
detec.on 
is 
done 
using 
overlaps 
method 
of 
Rectangle 
• Remember 
Texture 
Mapping? 
– Texture 
(image) 
– Mesh 
(rectangle) 
• Create 
rectangle 
for 
each 
texture 
• if(rect1.overlaps(rect2)) 
{ 
.. 
}
public class SimpleGame extends ApplicationAdapter { 
private Texture gorbaImage; 
private Rectangle gorbaRectangle; 
private Texture phoneImage; 
private Rectangle phoneRectangle; 
@Override 
public void create() { 
gorbaImage = new Texture(Gdx.files.internal("littlegorba.png")); 
phoneImage = new Texture(Gdx.files.internal("phone.png")); 
// new Rectangle (x, y, width, height) 
gorbaRectangle = new Rectangle(200,200,24,33); 
phoneRectangle = new Rectangle(300,300,17,45); 
} 
@Override 
public void render() { 
batch.begin(); 
batch.draw(gorbaImage, gorbaRectangle.x, gorbaRectangle.y); 
batch.draw(phoneImage, phoneRectangle.x, phoneRectangle.x); 
batch.end(); 
if(Gdx.input.isTouched()) { 
int realX = Gdx.input.getX(); 
int realY = Gdx.input.getY(); 
Vector3 touchPos = new Vector3(realX, realY, 0); 
camera.unproject(touchPos); 
gorbaRectangle.x = touchPos.x; 
gorbaRectangle.y = touchPos.y; 
} 
if(gorbaRectangle.overlaps(phoneRectangle)) { 
Gdx.app.debug("MyGame", "Crash!"); 
} 
} 
}
Texture 
+ 
Rectangle 
• Texture 
(image) 
and 
Rectangle 
(“paper”) 
go 
hand 
in 
hand 
• It 
would 
be 
great 
to 
map 
these 
into 
one 
class, 
for 
example 
Sprite 
– Don’t 
implement 
one, 
libgdx 
has 
Sprite 
J 
• hfp://libgdx.badlogicgames.com/nightlies/ 
docs/api/com/badlogic/gdx/graphics/g2d/ 
Sprite.html
Sprite 
usage 
Sprite gorbaSprite = new Sprite(new 
Texture(Gdx.files.internal("littlegorba.png")), 
24, 
33); 
// Rendering using SpriteBatch 
gorbaSprite.draw(batch); 
// Collision 
if( gorbaSprite.getBoundingRectangle() 
.overlaps(phoneSprite.getBoundingRectangle()) ) { 
// Crash 
}

More Related Content

What's hot

Technical Deep Dive into the New Prefab System
Technical Deep Dive into the New Prefab SystemTechnical Deep Dive into the New Prefab System
Technical Deep Dive into the New Prefab SystemUnity Technologies
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingTakashi Yoshinaga
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Unity Technologies
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲吳錫修 (ShyiShiou Wu)
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android GamesPlatty Soft
 
Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲吳錫修 (ShyiShiou Wu)
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.UA Mobile
 
Monogame Introduction (ENG)
Monogame Introduction (ENG)Monogame Introduction (ENG)
Monogame Introduction (ENG)Aloïs Deniel
 
PlayStation: Cutting Edge Techniques
PlayStation: Cutting Edge TechniquesPlayStation: Cutting Edge Techniques
PlayStation: Cutting Edge TechniquesSlide_N
 
Students to Business Day 2012: Rob Miles
Students to Business Day 2012: Rob MilesStudents to Business Day 2012: Rob Miles
Students to Business Day 2012: Rob MilesFrederik De Bruyne
 
Ujug07presentation
Ujug07presentationUjug07presentation
Ujug07presentationBill Adams
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded GraphicsAdil Jafri
 
Introducing the New Prefab Workflow - Unite LA
Introducing the New Prefab Workflow - Unite LAIntroducing the New Prefab Workflow - Unite LA
Introducing the New Prefab Workflow - Unite LAUnity Technologies
 
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)noorcon
 

What's hot (20)

Technical Deep Dive into the New Prefab System
Technical Deep Dive into the New Prefab SystemTechnical Deep Dive into the New Prefab System
Technical Deep Dive into the New Prefab System
 
HoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial MappingHoloLens Programming Tutorial: AirTap & Spatial Mapping
HoloLens Programming Tutorial: AirTap & Spatial Mapping
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
 
Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲Unity遊戲程式設計 - 2D Platformer遊戲
Unity遊戲程式設計 - 2D Platformer遊戲
 
Tools for developing Android Games
 Tools for developing Android Games Tools for developing Android Games
Tools for developing Android Games
 
Pygame presentation
Pygame presentationPygame presentation
Pygame presentation
 
Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲Unity遊戲程式設計(15) 實作Space shooter遊戲
Unity遊戲程式設計(15) 實作Space shooter遊戲
 
Unity 13 space shooter game
Unity 13 space shooter gameUnity 13 space shooter game
Unity 13 space shooter game
 
Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.Enhance your world with ARKit. UA Mobile 2017.
Enhance your world with ARKit. UA Mobile 2017.
 
Monogame Introduction (ENG)
Monogame Introduction (ENG)Monogame Introduction (ENG)
Monogame Introduction (ENG)
 
PlayStation: Cutting Edge Techniques
PlayStation: Cutting Edge TechniquesPlayStation: Cutting Edge Techniques
PlayStation: Cutting Edge Techniques
 
Windows Phone: From Idea to Published Game in 75 minutes
Windows Phone: From Idea to Published Game in 75 minutesWindows Phone: From Idea to Published Game in 75 minutes
Windows Phone: From Idea to Published Game in 75 minutes
 
Students to Business Day 2012: Rob Miles
Students to Business Day 2012: Rob MilesStudents to Business Day 2012: Rob Miles
Students to Business Day 2012: Rob Miles
 
Gaming Process
Gaming ProcessGaming Process
Gaming Process
 
7java Events
7java Events7java Events
7java Events
 
Ujug07presentation
Ujug07presentationUjug07presentation
Ujug07presentation
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded Graphics
 
Introducing the New Prefab Workflow - Unite LA
Introducing the New Prefab Workflow - Unite LAIntroducing the New Prefab Workflow - Unite LA
Introducing the New Prefab Workflow - Unite LA
 
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)
 

Similar to Implementing a Simple Game using libGDX

Getting Started with 3D Game Development on Nokia Series 40 Asha Phones
Getting Started with 3D Game Development on Nokia Series 40 Asha PhonesGetting Started with 3D Game Development on Nokia Series 40 Asha Phones
Getting Started with 3D Game Development on Nokia Series 40 Asha PhonesMicrosoft Mobile Developer
 
I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdffeelinggifts
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLgerbille
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTvineet raj
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsPrabindh Sundareson
 
Computer graphics
Computer graphicsComputer graphics
Computer graphicsamitsarda3
 
CS 354 Viewing Stuff
CS 354 Viewing StuffCS 354 Viewing Stuff
CS 354 Viewing StuffMark Kilgard
 
Computer graphics
Computer graphics Computer graphics
Computer graphics shafiq sangi
 
Game development with_lib_gdx
Game development with_lib_gdxGame development with_lib_gdx
Game development with_lib_gdxGabriel Grill
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 MinigamesSusan Gold
 
Advanced Game Development with the Mobile 3D Graphics API
Advanced Game Development with the Mobile 3D Graphics APIAdvanced Game Development with the Mobile 3D Graphics API
Advanced Game Development with the Mobile 3D Graphics APITomi Aarnio
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?Ankara JUG
 

Similar to Implementing a Simple Game using libGDX (20)

Getting Started with 3D Game Development on Nokia Series 40 Asha Phones
Getting Started with 3D Game Development on Nokia Series 40 Asha PhonesGetting Started with 3D Game Development on Nokia Series 40 Asha Phones
Getting Started with 3D Game Development on Nokia Series 40 Asha Phones
 
I wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdfI wanted to change the cloudsrectangles into an actuall image it do.pdf
I wanted to change the cloudsrectangles into an actuall image it do.pdf
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Developing games for Series 40 full-touch UI
Developing games for Series 40 full-touch UIDeveloping games for Series 40 full-touch UI
Developing games for Series 40 full-touch UI
 
Games 3 dl4-example
Games 3 dl4-exampleGames 3 dl4-example
Games 3 dl4-example
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORT
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI Platforms
 
Computer graphics
Computer graphicsComputer graphics
Computer graphics
 
CS 354 Viewing Stuff
CS 354 Viewing StuffCS 354 Viewing Stuff
CS 354 Viewing Stuff
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Game development with_lib_gdx
Game development with_lib_gdxGame development with_lib_gdx
Game development with_lib_gdx
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Graphics in C++
Graphics in C++Graphics in C++
Graphics in C++
 
Python gis
Python gisPython gis
Python gis
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 Minigames
 
Advanced Game Development with the Mobile 3D Graphics API
Advanced Game Development with the Mobile 3D Graphics APIAdvanced Game Development with the Mobile 3D Graphics API
Advanced Game Development with the Mobile 3D Graphics API
 
HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?HTML5 - Daha Flash bir web?
HTML5 - Daha Flash bir web?
 
Arkanoid Game
Arkanoid GameArkanoid Game
Arkanoid Game
 

More from Jussi Pohjolainen

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 
Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 
Quick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery MobileQuick Intro to JQuery and JQuery Mobile
Quick Intro to JQuery and JQuery Mobile
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
XAMPP
XAMPPXAMPP
XAMPP
 
Building Web Services
Building Web ServicesBuilding Web Services
Building Web Services
 
CSS
CSSCSS
CSS
 
Extensible Stylesheet Language
Extensible Stylesheet LanguageExtensible Stylesheet Language
Extensible Stylesheet Language
 

Recently uploaded

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Recently uploaded (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

Implementing a Simple Game using libGDX

  • 1. libGDX: Implemen.ng a Simple Game Jussi Pohjolainen Tampere University of Applied Sciences
  • 2. Starter Class: Desktop public class Main { public static void main(String[] args) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "Gorba's Revenge"; config.width = 800; config.height = 480; new LwjglApplication(new MyGame(), config); } } // In Android, the resolution is set by operating system!
  • 3. public class MyGame implements ApplicationListener { // Method called once when the application is created. public void create () { } // Method called by the game loop from the application // every time rendering should be performed. Game logic // updates are usually also performed in this method. public void render () { } // This method is called every time the game screen is re-sized // and the game is not in the paused state. It is also called once // just after the create() method. // The parameters are the new width and height the screen has been resized to in pixels. public void resize (int width, int height) { } // On Android this method is called when the Home button is // pressed or an incoming call is received. On desktop this is called // just before dispose() when exiting the application. // A good place to save the game state. public void pause () { } // This method is only called on Android, when the application // resumes from a paused state. public void resume () { } // Called when the application is destroyed. It is preceded by a call to pause(). public void dispose () { } }
  • 4.
  • 5. Assets • Drag sounds, images to android/assets folder – Desktop app has a link to that folder
  • 6. Asset loading public class MyGame implements ApplicationListener { private Texture gorbaImage; private Sound soundEffect; private Music backgroundMusic; @Override public void create() { // gorba.png uploaded to GPU and is ready to be used by OpenGL. Image format // must be .jpg, .png, .bmp gorbaImage = new Texture(Gdx.files.internal(”gorba.png")); // Stored in RAM soundEffect = Gdx.audio.newSound(Gdx.files.internal("beep.wav")); // Streamed from wherever it’s stored backgroundMusic = Gdx.audio.newMusic(Gdx.files.internal("ussranthem.mp3")); // start the playback of the background music immediately rainMusic.setLooping(true); rainMusic.play(); } public void dispose() { // Good practice to dispose (clean) assets gorbaImage.dispose(); soundEffect.dispose(); backgroundMusic.dispose(); }
  • 7. Rendering: Camera • Camera is like “virtual window into our world” – What part of the “world” is visible? • Camera – OrthographicCamera • When the human eye looks at a scene, objects in the distance appear smaller than objects close by. Orthographic projec.on ignores this effect – PerspectiveCamera • Closer objects appear bigger in Perspec.veCamera
  • 8. Using Camera public class SimpleGame extends ApplicationAdapter { private OrthographicCamera camera; @Override public void create() { camera = new OrthographicCamera(); // Sets this camera to an orthographic projection, // centered at (viewportWidth/2, viewportHeight/2), // with the y-axis pointing up or down. // true => y points down, false => y points up camera.setToOrtho(false, 800, 480);
  • 9. Word about OpenGL • OpenGL (Open Graphics Library) is a cross-­‐language, mul.-­‐plaRorm applica.on programming interface (API) for rendering 2D and 3D vector graphics. • The API is typically used to interact with a graphics processing unit (GPU), to achieve hardware-­‐ accelerated rendering. • Widely used in CAD, virtual reality, scien.fic visualiza.on, informa.on visualiza.on, flight simula.on, and video games. • libGDX uses OpenGL ES and has interface also for direct access for OpenGL
  • 10. Texture Mapping • A Texture wraps a standard OpenGL ES texture. – A texture is an OpenGL Object that contains one or more images that all have the same image format. • Image loaded into the GPU’s memory in raw format • Texture mapping is process of working out where in space the texture will be applied – “To s.ck a poster on a wall, one needs to figure out where on the wall he will be gluing the corners of the paper” – Space ó Wall – Mesh (Rectangle) ó Paper – Image on paper ó Texture
  • 11. SpriteBatch • SpriteBatch class takes care of texture mapping • Convenience class which makes drawing onto the screen easy
  • 12. public class SimpleGame extends ApplicationAdapter { private Texture gorbaImage; private OrthographicCamera camera; private SpriteBatch batch; @Override public void create() { camera = new OrthographicCamera(); batch = new SpriteBatch(); // Sets this camera to an orthographic projection, centered at (viewportWidth/2, viewportHeight/2), // with the y-axis pointing up or down. true => y points down, false => y points up camera.setToOrtho(false, 800, 480); gorbaImage = new Texture(Gdx.files.internal("littlegorba.png")); } @Override public void render() { // Let's use the coordinate system specified by the camera batch.setProjectionMatrix(camera.combined); // SpriteBatch is ready for commands batch.begin(); // Draw a texture to x = 100, y = 100 batch.draw(gorbaImage, 100, 100); batch.draw(gorbaImage, 140, 100); batch.draw(gorbaImage, 180, 100); batch.draw(gorbaImage, 220, 100); // No commands anymore, proceed to process the batch of commands // received batch.end(); } }
  • 13.
  • 14. Clear Screen @Override public void render() { // Direct OpenGL call // float red [0,1] // green // blue // alpha // https://www.opengl.org/sdk/docs/man/html/glClearColor.xhtml Gdx.gl.glClearColor(0, 0, 0.2f, 1); // Clear the screen with the color chosen // http://www.opengl.org/sdk/docs/man/html/glClear.xhtml Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // SpriteBatch is ready for commands batch.begin(); // Draw a texture to x = 100, y = 100 batch.draw(gorbaImage, 100, 100); batch.draw(gorbaImage, 140, 100); batch.draw(gorbaImage, 180, 100); batch.draw(gorbaImage, 220, 100); // No commands anymore, proceed to process the batch of commands // received batch.end(); }
  • 15. Gdx.input • Ge]ng input from user is very easy • Touch – Gdx.input.isTouched() – Gdx.input.getX() – Gdx.input.getY() • Accelerometer – Gdx.input.getAccelerometerX() – Gdx.input.getAccelerometerY() – Gdx.input.getAccelerometerZ()
  • 16. About Resolu.on • Game can be cross-­‐plaRorm, what is the resolu.on? • We have two resolu.ons – The real resolu.on – The world resolu.on • Mapping must be done between these two!
  • 17. Real resolu.on 0,0 World resolu.on 0,480 Real resolu.on 0,480 World resolu.on 0,0 Window resolu.on 800 x 480 World resolu.on set to 800 x 480
  • 18. Real resolu.on 0,0 World resolu.on 0,480 Real resolu.on 0,384 World resolu.on 0,0 Window width 640 x 384 World resolu.on set to 800 x 480
  • 19. Conversion @Override public void render() { if(Gdx.input.isTouched()) { int realX = Gdx.input.getX(); int realY = Gdx.input.getY(); // Encapsulated 3D Vector, only 2D is used // Vectors can be used for represent a direction and position // Bad practice to instantiate every render – call! Vector3 touchPos = new Vector3(realX, realY, 0); // Function to translate a point given in screen coordinates to world space. camera.unproject(touchPos); Gdx.app.setLogLevel(Logger.DEBUG); Gdx.app.debug("MyGame", "real X = " + realX); Gdx.app.debug("MyGame", "real Y = " + realY); Gdx.app.debug("MyGame", "world X = " + touchPos.x); Gdx.app.debug("MyGame", "world Y = " + touchPos.y); } }
  • 20. Collision • Simple collision detec.on is done using overlaps method of Rectangle • Remember Texture Mapping? – Texture (image) – Mesh (rectangle) • Create rectangle for each texture • if(rect1.overlaps(rect2)) { .. }
  • 21. public class SimpleGame extends ApplicationAdapter { private Texture gorbaImage; private Rectangle gorbaRectangle; private Texture phoneImage; private Rectangle phoneRectangle; @Override public void create() { gorbaImage = new Texture(Gdx.files.internal("littlegorba.png")); phoneImage = new Texture(Gdx.files.internal("phone.png")); // new Rectangle (x, y, width, height) gorbaRectangle = new Rectangle(200,200,24,33); phoneRectangle = new Rectangle(300,300,17,45); } @Override public void render() { batch.begin(); batch.draw(gorbaImage, gorbaRectangle.x, gorbaRectangle.y); batch.draw(phoneImage, phoneRectangle.x, phoneRectangle.x); batch.end(); if(Gdx.input.isTouched()) { int realX = Gdx.input.getX(); int realY = Gdx.input.getY(); Vector3 touchPos = new Vector3(realX, realY, 0); camera.unproject(touchPos); gorbaRectangle.x = touchPos.x; gorbaRectangle.y = touchPos.y; } if(gorbaRectangle.overlaps(phoneRectangle)) { Gdx.app.debug("MyGame", "Crash!"); } } }
  • 22. Texture + Rectangle • Texture (image) and Rectangle (“paper”) go hand in hand • It would be great to map these into one class, for example Sprite – Don’t implement one, libgdx has Sprite J • hfp://libgdx.badlogicgames.com/nightlies/ docs/api/com/badlogic/gdx/graphics/g2d/ Sprite.html
  • 23. Sprite usage Sprite gorbaSprite = new Sprite(new Texture(Gdx.files.internal("littlegorba.png")), 24, 33); // Rendering using SpriteBatch gorbaSprite.draw(batch); // Collision if( gorbaSprite.getBoundingRectangle() .overlaps(phoneSprite.getBoundingRectangle()) ) { // Crash }