SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Crea%ng	
  Asha	
  Games:	
  

Game	
  Pausing,	
  Device	
  Orienta%on,	
  Sensors,	
  Gestures	
  

Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
GAME	
  PAUSING	
  
About	
  Game	
  Pausing	
  
•  Pause	
  game	
  when	
  
–  Phone	
  rings	
  
–  Back	
  –	
  buHon	
  is	
  pressed	
  

•  Remember	
  that	
  MIDlet's	
  pauseApp	
  –	
  method	
  
is	
  never	
  called!	
  
•  In	
  GameCanvas,	
  implement	
  following	
  
–  public void showNotify() // resume
–  public void hideNotify() // pause
About	
  Gameloop	
  and	
  Threading	
  
•  Gameloop	
  is	
  implemented	
  using	
  Threading	
  
–  Thread thread = new Thread(Runnable x);
–  thread.start(); // calls run()

•  Gameloop	
  usually:	
  
–  while(gameIsOn) { ….
Thread.sleep(ticks); }

•  How	
  to	
  pause	
  the	
  current	
  thread	
  in	
  midp?	
  
Synchroniza%on	
  
•  Let's	
  first	
  look	
  at	
  synchroniza5on.	
  
•  There	
  might	
  be	
  a	
  problem,	
  if	
  two	
  threads	
  accesses	
  the	
  same	
  
data	
  
–  Two	
  people	
  each	
  have	
  a	
  ATM	
  cards	
  that	
  are	
  linked	
  to	
  only	
  one	
  account	
  
–  What	
  happens	
  when	
  these	
  two	
  people	
  accesses	
  the	
  account	
  at	
  the	
  
same	
  %me?	
  

•  Withdrawal	
  is	
  two-­‐step	
  process	
  
–  Check	
  the	
  balance	
  
–  If	
  there's	
  enough	
  money	
  int	
  the	
  account,	
  make	
  the	
  withdrawal	
  

•  What	
  happens	
  if	
  1	
  and	
  2	
  are	
  separated?	
  
Locks	
  
•  We	
  must	
  guarantee	
  that	
  the	
  two	
  steps	
  are	
  
never	
  split	
  apart.	
  Use	
  synchronized	
  keyword	
  
•  Synchroniza%on	
  works	
  with	
  locks.	
  Every	
  
object	
  has	
  a	
  lock.	
  If	
  one	
  thread	
  has	
  picked	
  up	
  
the	
  lock,	
  no	
  other	
  thread	
  can	
  use	
  the	
  
synchronized	
  code.	
  
Examples	
  
•  Let's	
  look	
  at	
  some	
  synchroniza%on	
  examples	
  
–  https://dl.dropboxusercontent.com/u/
874087/game-programming/examples/
threading/Synchronized1.java

•  See	
  also	
  
–  Synchronized2.java -> Synchronized5.java
wait()	
  
•  Object	
  class	
  holds	
  a	
  method	
  wait()	
  
–  Causes	
  the	
  current	
  thread	
  to	
  wait	
  un%l	
  another	
  
thread	
  invokes	
  the	
  no%fy()	
  method	
  for	
  this	
  object	
  

•  So	
  when	
  calling	
  wait()	
  it	
  pauses	
  the	
  current	
  
thread	
  and	
  waits	
  that	
  some	
  other	
  thread	
  calls	
  
no%fy()	
  or	
  no%fyAll()!	
  
// NOTICE! This example does not work, all exception handling and synchronized blocks
// are missing
class MyApp {
public static void main(String [] args) {
new MyApp();
}
public MyApp() {
MyThread mythread;
Thread thread = new Thread(mythread = new MyThread());
thread.start();
System.out.println("Sleeping");
Thread.sleep(2000);
// Resume from wait! Calls notify from the object that is in wait…
mythread.notify();
}
}
class MyThread implements Runnable {
public void run() {
// Let's wait until someone calls notify
wait();
System.out.println("Resumed!");
}
}
wait()	
  
•  When	
  calling	
  wait	
  and	
  no%fy,	
  it	
  must	
  be	
  inside	
  
synchronized	
  block.	
  
	
  
synchronized(this) {
// Before calling notify, the thread calling this must
// own a lock.
notify();
}
synchronized(this) {
wait();
}

	
  
Game	
  Pausing	
  in	
  MIDlet	
  
•  In	
  GameCanvas,	
  following	
  methods	
  are	
  called	
  
when	
  phone	
  rings.	
  
	
  	
  	
  	
  	
  	
  
// Phone rings
public void hideNotify()	
  {	
  
pause(); // pause game – my own method
}	
  
	
  
// Phone ends
public void showNotify()	
  {	
  
resume(); // resume game – my own method
}
pause() and	
  resume()
public void resume() {
isPause = false;
synchronized(this) {
notify(); // Notify that waiting thread can
// continue.
}
}
public void pause() {
isPause = true;
}
Game	
  Loop	
  
public void run() {
int i = 0;
while(true) {
checkIfPause();
checkCollisions();
moveSprites();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void checkIfPause() {
synchronized(this) {
while(isPause) { // while, just in case
try {
wait(); // Wait in current thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Back	
  BuHon	
  to	
  Game	
  Canvas	
  
Command backCommand = new Command("Back",
Command.BACK,
0);
addCommand(backCommand);
setCommandListener(this);

// and the listener method
public void commandAction(Command c, Displayable d) {
if(isPause) {
midlet.notifyDestroyed();
} else {
pause();
}
}
DEVICE	
  ORIENTATION	
  
Adjus%ng	
  Device's	
  Orienta%on	
  
•  MIDlets	
  can	
  use	
  Orienta5on	
  API	
  to	
  
–  Change	
  their	
  UI	
  orienta%on	
  
–  Determine	
  their	
  current	
  UI	
  orienta%on	
  
–  Determine	
  the	
  current	
  display	
  orienta%on	
  
–  Receive	
  a	
  no%fica%on	
  whenever	
  the	
  display	
  
orienta%on	
  changes	
  

•  When	
  MIDlet	
  changes	
  it's	
  UI	
  orienta%on,	
  it	
  has	
  
to	
  redraw	
  the	
  low-­‐level	
  components	
  that	
  it	
  
uses.	
  
Supported	
  Orienta%ons	
  
• 
• 
• 
• 

ORIENTATION_LANDSCAPE
ORIENTATION_LANDSCAPE_180
ORIENTATION_PORTRAIT
ORIENTATION_PORTRAIT_180
Se^ng	
  UI	
  Orienta%on	
  
•  Add	
  following	
  to	
  JAD	
  file:	
  
–  Nokia-MIDlet-App-Orientation: manual

•  Now	
  it	
  supports	
  both	
  portrait	
  and	
  landscape	
  
modes	
  
•  Add	
  orienta%on	
  listener	
  
–  Orientation.addOrientationListener(orientationListener);
Orienta%on	
  Listener	
  Callback	
  
/** Orientation listener callback */
public void displayOrientationChanged( int newDisplayOrientation ){
/** Check display orientation */
switch( newDisplayOrientation ){
case Orientation.ORIENTATION_PORTRAIT:
case Orientation.ORIENTATION_PORTRAIT_180:
/** Change MIDlet UI orientation to portrait */
Orientation.setAppOrientation(Orientation.ORIENTATION_PORTRAIT);
break;
case Orientation.ORIENTATION_LANDSCAPE:
case Orientation.ORIENTATION_LANDSCAPE_180:
/** Change MIDlet UI orientation to landscape */
Orientation.setAppOrientation(Orientation.ORIENTATION_LANDSCAPE);
break;
}
}
sizeChanged()
•  When	
  UI	
  Orienta%on	
  changes:	
  
	
  
/** Java platform will call this when UI orientation has been changed */
protected void sizeChanged( int w, int h ){
/** Acquiring new Graphics Object since old is not valid anymore */
g = getGraphics( );
canDraw = true;
}
MOBILE	
  SENSOR	
  API	
  
Mobile	
  Sensors	
  
•  Mobile	
  Sensor	
  API	
  allows	
  MIDlets	
  to	
  fetch	
  
data	
  from	
  the	
  sensors	
  of	
  the	
  mobile	
  device	
  
•  Sensor	
  consists	
  of	
  one	
  or	
  more	
  channels,	
  in	
  
accelerometer	
  you	
  will	
  get	
  data	
  from	
  three	
  
channels	
  (x,	
  y	
  and	
  z)	
  
•  Sensors	
  have	
  common	
  proper%es:	
  	
  
–  accuracy	
  
–  max	
  and	
  min	
  value	
  
Available	
  Sensors	
  in	
  Asha	
  50X	
  
•  Accelera5on	
  sensor	
  	
  
–  measures	
  accelera%on	
  in	
  SI	
  units	
  for	
  x,	
  y	
  and	
  z	
  -­‐	
  axis.	
  

•  Orienta5on	
  sensor	
  
–  provides	
  informa%on	
  of	
  devices	
  current	
  orienta%on	
  posi%on.	
  

•  Rota5on	
  sensor	
  	
  
–  provides	
  informa%on	
  of	
  devices	
  current	
  rota%on	
  degree.	
  

•  Double	
  tapping	
  sensor	
  	
  
–  provides	
  informa%on	
  of	
  double	
  taps	
  occurred	
  on	
  the	
  phone	
  sides.	
  

•  Proximity	
  sensor	
  	
  
–  indicates	
  if	
  an	
  obstacle	
  is	
  right	
  in	
  front	
  of	
  it	
  

•  BaLery	
  sensor	
  	
  
–  shows	
  baHery	
  charge	
  level	
  in	
  percentage.	
  Sensor	
  is	
  always	
  on.	
  

•  Charger	
  sensor	
  
–  shows	
  whether	
  charger	
  is	
  connected.	
  Sensor	
  is	
  always	
  on.	
  

•  Signal	
  strength	
  sensor	
  
–  shows	
  strength	
  of	
  network	
  connec%on	
  in	
  percentage.	
  Sensor	
  is	
  always	
  on.	
  
Using	
  Sensors	
  
Finding	
  and	
  Iden%fying	
  a	
  Sensor	
  
// Find all sensors
SensorInfo[] sensorInfos =
SensorManager.findSensors(null, null);
for(int i=0; i<sensorInfos.length; i++) {
SensorInfo si = sensorInfos[i];
System.out.println(si.getUrl());
}
Finding	
  and	
  Iden%fying	
  a	
  Sensor	
  
// Sensor type (quantity):
//
acceleration
//
orientation
//
rotation
//
double_tap
//
proximity
//
battery_charge
//
charger_state
//
network_field_intensity
//
null
String type = "acceleration";
// Sensor Context type
//
ambient
//
device
//
user
//
vehicle
//
null
String contextType = "user";
// Fetch all sensors with given information, should find only one.
SensorInfo[] si = SensorManager.findSensors(type, contextType);
// Retrieve the sensor url.
String sensorURL = si[0].getUrl();
Opening	
  a	
  sensor	
  connec%on	
  
{
try {
// This may not be a good idea, fetch the URL from sensorinfo using sensor quantity and
// context type
String sensorURL = "sensor:acceleration;contextType=user;model=Nokia;location=NoLoc";
// How fast data is sent to listener!
final int BUFFER_SIZE = 1;
SensorConnection sensorConnection = (SensorConnection)Connector.open(sensorURL);
// this = any object that implements DataListener
sensorConnection.setDataListener(this, BUFFER_SIZE);
} catch (IOException e) {
e.printStackTrace();
}
}
// Datalistener interface method
public void dataReceived(SensorConnection sensor, Data[] data,
boolean isDataLost) {
System.out.println("Here!");
}
Case:	
  Accelera%on	
  listening	
  
public void dataReceived(SensorConnection sensor, Data[] data,
boolean isDataLost) {
// We have three channels.
System.out.println("Channel amount: " + data.length);
// Channel is Data object
Data x = data[0];
// Each channel may hold several values. In this case
// only one.
double [] values = x.getDoubleValues();
System.out.println("Number of values " + values.length);
// And the value is:
System.out.println("x = " + values[0]);
// Let's fetch the rest (y and z) in just on line
System.out.println("y = " + data[1].getDoubleValues()[0]);
System.out.println("z = " + data[2].getDoubleValues()[0]);
}
Case:	
  Accelera%on	
  listening	
  
public void dataReceived(SensorConnection sensor, Data[] data,
boolean isDataLost) {
System.out.println("x = " + data[0].getDoubleValues()[0]);
System.out.println("y = " + data[1].getDoubleValues()[0]);
System.out.println("z = " + data[2].getDoubleValues()[0]);
}
Closing	
  connec%on	
  
•  Remember	
  to	
  close	
  the	
  connec%on	
  if	
  not	
  
needed!	
  
–  sensorConnection.close();
GESTURES	
  API	
  
Really	
  Easy	
  to	
  Use	
  
// STEP 1: Defines a GestureInteractiveZone for the
// whole screen and all Gesture types.
GestureInteractiveZone giz = new
GestureInteractiveZone( GestureInteractiveZone.GESTURE_ALL );
// STEP 2: Register the GestureInteractiveZones for the
// GameCanvas object this.
GestureRegistrationManager.register( this, giz );
// STEP 3: Set the listener, source is this gamecanvas
// and listener is this also
GestureRegistrationManager.setListener(this, this);
Listener	
  
public void gestureAction(Object container,
GestureInteractiveZone gestureInteractiveZone,
GestureEvent gestureEvent) {
switch(gestureEvent.getType()) {
case GestureInteractiveZone.GESTURE_TAP:
Debug.printInfo("MyGameCanvas", "gestureAction", "TAP", 2);
break;
...
case GestureInteractiveZone.GESTURE_LONG_PRESS:
Debug.printInfo("MyGameCanvas", "gestureAction", "LONG PRESS", 2);
break;
}
}
Listener	
  
public void gestureAction(Object container,
GestureInteractiveZone gestureInteractiveZone,
GestureEvent gestureEvent) {
switch(gestureEvent.getType()) {
...
case GestureInteractiveZone.GESTURE_FLICK:
Debug.printInfo("MyGameCanvas", "gestureAction", "FLICK", 2);
Debug.printInfo("MyGameCanvas", "gestureAction",
"flick speed = " + gestureEvent.getFlickSpeed(), 2);
Debug.printInfo("MyGameCanvas", "gestureAction",
"flick direction = " + gestureEvent.getFlickDirection(), 2);
break;
}
}

Mais conteúdo relacionado

Mais procurados

Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
sumitjoshi01
 

Mais procurados (20)

Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Knock, knock, who is there? Doze.
Knock, knock, who is there? Doze.Knock, knock, who is there? Doze.
Knock, knock, who is there? Doze.
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adapters
 
7java Events
7java Events7java Events
7java Events
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
 
JCrete Embedded Java Workshop
JCrete Embedded Java WorkshopJCrete Embedded Java Workshop
JCrete Embedded Java Workshop
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Guide to Destroying Codebases The Demise of Clever Code
Guide to Destroying Codebases   The Demise of Clever CodeGuide to Destroying Codebases   The Demise of Clever Code
Guide to Destroying Codebases The Demise of Clever Code
 
Scene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game EnginesScene Graphs & Component Based Game Engines
Scene Graphs & Component Based Game Engines
 
Using Android Things to Detect & Exterminate Reptilians
Using Android Things to Detect & Exterminate ReptiliansUsing Android Things to Detect & Exterminate Reptilians
Using Android Things to Detect & Exterminate Reptilians
 
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...Fullstack Conference -  Proxies before proxies: The hidden gems of Javascript...
Fullstack Conference - Proxies before proxies: The hidden gems of Javascript...
 
Eddystone beacons demo
Eddystone beacons demoEddystone beacons demo
Eddystone beacons demo
 
The 2016 Android Developer Toolbox [NANTES]
The 2016 Android Developer Toolbox [NANTES]The 2016 Android Developer Toolbox [NANTES]
The 2016 Android Developer Toolbox [NANTES]
 
TestowanieIoT2016
TestowanieIoT2016TestowanieIoT2016
TestowanieIoT2016
 
State management in android applications
State management in android applicationsState management in android applications
State management in android applications
 
What’s new in Android JetPack
What’s new in Android JetPackWhat’s new in Android JetPack
What’s new in Android JetPack
 

Destaque (7)

Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
ADT02 - Java 8 Lambdas and the Streaming API
ADT02 - Java 8 Lambdas and the Streaming APIADT02 - Java 8 Lambdas and the Streaming API
ADT02 - Java 8 Lambdas and the Streaming API
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
iOS Selectors Blocks and Delegation
iOS Selectors Blocks and DelegationiOS Selectors Blocks and Delegation
iOS Selectors Blocks and Delegation
 
Compiling Qt Apps
Compiling Qt AppsCompiling Qt Apps
Compiling Qt Apps
 

Semelhante a Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures

02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
TECOS
 
DEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking ForDEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking For
Michael Scovetta
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
mukul bhardwaj
 

Semelhante a Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures (20)

Mobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptMobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScript
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphores
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Embedded software development using BDD
Embedded software development using BDDEmbedded software development using BDD
Embedded software development using BDD
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
 
Till applet skeleton
Till applet skeletonTill applet skeleton
Till applet skeleton
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android Development
 
Behavioral Design Patterns
Behavioral Design PatternsBehavioral Design Patterns
Behavioral Design Patterns
 
DEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking ForDEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking For
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
 
Contiki Operating system tutorial
Contiki Operating system tutorialContiki Operating system tutorial
Contiki Operating system tutorial
 
Letselectronic.blogspot.com robotic arm based on atmega mcu controlled by win...
Letselectronic.blogspot.com robotic arm based on atmega mcu controlled by win...Letselectronic.blogspot.com robotic arm based on atmega mcu controlled by win...
Letselectronic.blogspot.com robotic arm based on atmega mcu controlled by win...
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
 
Background Fetch - the most powerful API you've never heard of
Background Fetch - the most powerful API you've never heard ofBackground Fetch - the most powerful API you've never heard of
Background Fetch - the most powerful API you've never heard of
 
Day 2 slides UNO summer 2010 robotics workshop
Day 2 slides UNO summer 2010 robotics workshopDay 2 slides UNO summer 2010 robotics workshop
Day 2 slides UNO summer 2010 robotics workshop
 
Java applet
Java appletJava applet
Java applet
 

Mais de Jussi Pohjolainen

Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
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
Jussi Pohjolainen
 
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
Jussi Pohjolainen
 

Mais de 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
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
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
 
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
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
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
 

Último

Último (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures

  • 1. Crea%ng  Asha  Games:   Game  Pausing,  Device  Orienta%on,  Sensors,  Gestures   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 3. About  Game  Pausing   •  Pause  game  when   –  Phone  rings   –  Back  –  buHon  is  pressed   •  Remember  that  MIDlet's  pauseApp  –  method   is  never  called!   •  In  GameCanvas,  implement  following   –  public void showNotify() // resume –  public void hideNotify() // pause
  • 4. About  Gameloop  and  Threading   •  Gameloop  is  implemented  using  Threading   –  Thread thread = new Thread(Runnable x); –  thread.start(); // calls run() •  Gameloop  usually:   –  while(gameIsOn) { …. Thread.sleep(ticks); } •  How  to  pause  the  current  thread  in  midp?  
  • 5. Synchroniza%on   •  Let's  first  look  at  synchroniza5on.   •  There  might  be  a  problem,  if  two  threads  accesses  the  same   data   –  Two  people  each  have  a  ATM  cards  that  are  linked  to  only  one  account   –  What  happens  when  these  two  people  accesses  the  account  at  the   same  %me?   •  Withdrawal  is  two-­‐step  process   –  Check  the  balance   –  If  there's  enough  money  int  the  account,  make  the  withdrawal   •  What  happens  if  1  and  2  are  separated?  
  • 6. Locks   •  We  must  guarantee  that  the  two  steps  are   never  split  apart.  Use  synchronized  keyword   •  Synchroniza%on  works  with  locks.  Every   object  has  a  lock.  If  one  thread  has  picked  up   the  lock,  no  other  thread  can  use  the   synchronized  code.  
  • 7. Examples   •  Let's  look  at  some  synchroniza%on  examples   –  https://dl.dropboxusercontent.com/u/ 874087/game-programming/examples/ threading/Synchronized1.java •  See  also   –  Synchronized2.java -> Synchronized5.java
  • 8. wait()   •  Object  class  holds  a  method  wait()   –  Causes  the  current  thread  to  wait  un%l  another   thread  invokes  the  no%fy()  method  for  this  object   •  So  when  calling  wait()  it  pauses  the  current   thread  and  waits  that  some  other  thread  calls   no%fy()  or  no%fyAll()!  
  • 9. // NOTICE! This example does not work, all exception handling and synchronized blocks // are missing class MyApp { public static void main(String [] args) { new MyApp(); } public MyApp() { MyThread mythread; Thread thread = new Thread(mythread = new MyThread()); thread.start(); System.out.println("Sleeping"); Thread.sleep(2000); // Resume from wait! Calls notify from the object that is in wait… mythread.notify(); } } class MyThread implements Runnable { public void run() { // Let's wait until someone calls notify wait(); System.out.println("Resumed!"); } }
  • 10. wait()   •  When  calling  wait  and  no%fy,  it  must  be  inside   synchronized  block.     synchronized(this) { // Before calling notify, the thread calling this must // own a lock. notify(); } synchronized(this) { wait(); }  
  • 11. Game  Pausing  in  MIDlet   •  In  GameCanvas,  following  methods  are  called   when  phone  rings.               // Phone rings public void hideNotify()  {   pause(); // pause game – my own method }     // Phone ends public void showNotify()  {   resume(); // resume game – my own method }
  • 12. pause() and  resume() public void resume() { isPause = false; synchronized(this) { notify(); // Notify that waiting thread can // continue. } } public void pause() { isPause = true; }
  • 13. Game  Loop   public void run() { int i = 0; while(true) { checkIfPause(); checkCollisions(); moveSprites(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private void checkIfPause() { synchronized(this) { while(isPause) { // while, just in case try { wait(); // Wait in current thread } catch (InterruptedException e) { e.printStackTrace(); } } } }
  • 14. Back  BuHon  to  Game  Canvas   Command backCommand = new Command("Back", Command.BACK, 0); addCommand(backCommand); setCommandListener(this); // and the listener method public void commandAction(Command c, Displayable d) { if(isPause) { midlet.notifyDestroyed(); } else { pause(); } }
  • 16. Adjus%ng  Device's  Orienta%on   •  MIDlets  can  use  Orienta5on  API  to   –  Change  their  UI  orienta%on   –  Determine  their  current  UI  orienta%on   –  Determine  the  current  display  orienta%on   –  Receive  a  no%fica%on  whenever  the  display   orienta%on  changes   •  When  MIDlet  changes  it's  UI  orienta%on,  it  has   to  redraw  the  low-­‐level  components  that  it   uses.  
  • 18. Se^ng  UI  Orienta%on   •  Add  following  to  JAD  file:   –  Nokia-MIDlet-App-Orientation: manual •  Now  it  supports  both  portrait  and  landscape   modes   •  Add  orienta%on  listener   –  Orientation.addOrientationListener(orientationListener);
  • 19. Orienta%on  Listener  Callback   /** Orientation listener callback */ public void displayOrientationChanged( int newDisplayOrientation ){ /** Check display orientation */ switch( newDisplayOrientation ){ case Orientation.ORIENTATION_PORTRAIT: case Orientation.ORIENTATION_PORTRAIT_180: /** Change MIDlet UI orientation to portrait */ Orientation.setAppOrientation(Orientation.ORIENTATION_PORTRAIT); break; case Orientation.ORIENTATION_LANDSCAPE: case Orientation.ORIENTATION_LANDSCAPE_180: /** Change MIDlet UI orientation to landscape */ Orientation.setAppOrientation(Orientation.ORIENTATION_LANDSCAPE); break; } }
  • 20. sizeChanged() •  When  UI  Orienta%on  changes:     /** Java platform will call this when UI orientation has been changed */ protected void sizeChanged( int w, int h ){ /** Acquiring new Graphics Object since old is not valid anymore */ g = getGraphics( ); canDraw = true; }
  • 22. Mobile  Sensors   •  Mobile  Sensor  API  allows  MIDlets  to  fetch   data  from  the  sensors  of  the  mobile  device   •  Sensor  consists  of  one  or  more  channels,  in   accelerometer  you  will  get  data  from  three   channels  (x,  y  and  z)   •  Sensors  have  common  proper%es:     –  accuracy   –  max  and  min  value  
  • 23. Available  Sensors  in  Asha  50X   •  Accelera5on  sensor     –  measures  accelera%on  in  SI  units  for  x,  y  and  z  -­‐  axis.   •  Orienta5on  sensor   –  provides  informa%on  of  devices  current  orienta%on  posi%on.   •  Rota5on  sensor     –  provides  informa%on  of  devices  current  rota%on  degree.   •  Double  tapping  sensor     –  provides  informa%on  of  double  taps  occurred  on  the  phone  sides.   •  Proximity  sensor     –  indicates  if  an  obstacle  is  right  in  front  of  it   •  BaLery  sensor     –  shows  baHery  charge  level  in  percentage.  Sensor  is  always  on.   •  Charger  sensor   –  shows  whether  charger  is  connected.  Sensor  is  always  on.   •  Signal  strength  sensor   –  shows  strength  of  network  connec%on  in  percentage.  Sensor  is  always  on.  
  • 25. Finding  and  Iden%fying  a  Sensor   // Find all sensors SensorInfo[] sensorInfos = SensorManager.findSensors(null, null); for(int i=0; i<sensorInfos.length; i++) { SensorInfo si = sensorInfos[i]; System.out.println(si.getUrl()); }
  • 26. Finding  and  Iden%fying  a  Sensor   // Sensor type (quantity): // acceleration // orientation // rotation // double_tap // proximity // battery_charge // charger_state // network_field_intensity // null String type = "acceleration"; // Sensor Context type // ambient // device // user // vehicle // null String contextType = "user"; // Fetch all sensors with given information, should find only one. SensorInfo[] si = SensorManager.findSensors(type, contextType); // Retrieve the sensor url. String sensorURL = si[0].getUrl();
  • 27. Opening  a  sensor  connec%on   { try { // This may not be a good idea, fetch the URL from sensorinfo using sensor quantity and // context type String sensorURL = "sensor:acceleration;contextType=user;model=Nokia;location=NoLoc"; // How fast data is sent to listener! final int BUFFER_SIZE = 1; SensorConnection sensorConnection = (SensorConnection)Connector.open(sensorURL); // this = any object that implements DataListener sensorConnection.setDataListener(this, BUFFER_SIZE); } catch (IOException e) { e.printStackTrace(); } } // Datalistener interface method public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) { System.out.println("Here!"); }
  • 28. Case:  Accelera%on  listening   public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) { // We have three channels. System.out.println("Channel amount: " + data.length); // Channel is Data object Data x = data[0]; // Each channel may hold several values. In this case // only one. double [] values = x.getDoubleValues(); System.out.println("Number of values " + values.length); // And the value is: System.out.println("x = " + values[0]); // Let's fetch the rest (y and z) in just on line System.out.println("y = " + data[1].getDoubleValues()[0]); System.out.println("z = " + data[2].getDoubleValues()[0]); }
  • 29. Case:  Accelera%on  listening   public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) { System.out.println("x = " + data[0].getDoubleValues()[0]); System.out.println("y = " + data[1].getDoubleValues()[0]); System.out.println("z = " + data[2].getDoubleValues()[0]); }
  • 30. Closing  connec%on   •  Remember  to  close  the  connec%on  if  not   needed!   –  sensorConnection.close();
  • 32. Really  Easy  to  Use   // STEP 1: Defines a GestureInteractiveZone for the // whole screen and all Gesture types. GestureInteractiveZone giz = new GestureInteractiveZone( GestureInteractiveZone.GESTURE_ALL ); // STEP 2: Register the GestureInteractiveZones for the // GameCanvas object this. GestureRegistrationManager.register( this, giz ); // STEP 3: Set the listener, source is this gamecanvas // and listener is this also GestureRegistrationManager.setListener(this, this);
  • 33. Listener   public void gestureAction(Object container, GestureInteractiveZone gestureInteractiveZone, GestureEvent gestureEvent) { switch(gestureEvent.getType()) { case GestureInteractiveZone.GESTURE_TAP: Debug.printInfo("MyGameCanvas", "gestureAction", "TAP", 2); break; ... case GestureInteractiveZone.GESTURE_LONG_PRESS: Debug.printInfo("MyGameCanvas", "gestureAction", "LONG PRESS", 2); break; } }
  • 34. Listener   public void gestureAction(Object container, GestureInteractiveZone gestureInteractiveZone, GestureEvent gestureEvent) { switch(gestureEvent.getType()) { ... case GestureInteractiveZone.GESTURE_FLICK: Debug.printInfo("MyGameCanvas", "gestureAction", "FLICK", 2); Debug.printInfo("MyGameCanvas", "gestureAction", "flick speed = " + gestureEvent.getFlickSpeed(), 2); Debug.printInfo("MyGameCanvas", "gestureAction", "flick direction = " + gestureEvent.getFlickDirection(), 2); break; } }