Inspedio Engine Tutorial : Index

Hello Guys. Welcome to Inspedio Engine and have fun learning.

This is the index page of Tutorial. Choose what you want to learn.

  1. Introduction.
  2. Getting Started, Setting up tools.
  3. Running Basic Game
  4. Understanding Basic Concept.
  5. Knowing your Game Object.
  6. Controlling object with Game Action.
  7. Playing Animation.
  8. The Magic of Callback.
  9. Customize game object.
  10. Creating Multi-Sprite Object.
  11. Control The Game with Global class.
  12. Handling User Input.
  13. Detecting Collision.
  14. Playing Sound & Music.
  15. Enhancing Game Loader.
  16. Saving your Game Data.
  17. Toying with Camera.
  18. Customize Pause Behavior
  19. Optimizing your Game Performance.
  20. Optimizing your Game Size.
  21. Configuring In-app Purchase.
  22. Hacking The Engine.
  23. Afterthought

Online Documentation can be found here.

Offline Documentation can be downloaded here

Jangan Diam dan Mendiamkan

Intro

Pemilihan Presiden Indonesia hanya kurang dari sebulan. Hanya ada 2 pasangan capres-cawapres yang dapat dipilih oleh rakyat Indonesia, Prabowo-Hatta Rajasa, atau Jokowi-JK. Tadinya saya berniat untuk golput, karena jagoan saya, Anies Baswedan gagal menjadi capres. Tapi kemudian saya terngiang perkataan Anies Baswedan.

Orang jahat bisa berkuasa karena orang baik diam dan mendiamkan. Jangan menjadi orang yang hanya menonton, karena itu berarti anda membiarkan orang jahat menang

Banyak dari orang-orang baik yang melihat kedua pasangan capres tidak memenuhi kriteria mereka. Saya pun demikian, karena baik Prabowo-Hatta dan Jokowi-JK memiliki kekurangan fatal yang tidak dapat saya terima. Tapi kita sedang memilih presiden, bukan memilih manusia sempurna. Dan fakta yang terjadi, hanya ada 2 pasangan tersebut. Sehingga kita harus memilih pasangan yang less-evil.

Post ini saya tujukan untuk mengungkapkan analisa saya, beserta alur pemikiran saya pribadi dalam memilih pasangan capres-cawapres. Harapan saya, semoga orang-orang baik yang memilih untuk golput karena tidak cocok dengan capres yang ada, merubah pikirannya dan melakukan analisa versi mereka sendiri. Jangan diam dan mendiamkan. Lebih baik memilih yang menurut kita paling baik, walaupun pilihan kita belum tentu yang terbaik, daripada tidak memilih dan mendiamkan yang buruk berkuasa.

Kriteria Negatif

Karena saya hendak memilih pasangan yang less-evil, maka saya membuat list kriteria negatif yang dimiliki kedua pasangan, untuk kemudian saya analisa dan pilih kriteria mana yang lebih dapat ditolerir bagi saya.

Prabowo – Hatta Rajasa:

  1. Mengeluarkan modal besar untuk kampanye. Jauh jauh sebelum pilpres 2014, saya banyak melihat iklan kampanye Prabowo Subianto. Bayangkan berapa banyak uang yang ia keluarkan untuk itu.
  2. Minim Prestasi. Di luar karirnya sebagai TNI, prabowo nyaris tidak memiliki prestasi yang signifikan, yang menunjukkan kompetensinya sebagai presiden nantinya.
  3. Potensial Masalah. Masa lalu prabowo yang kelam dan belum terungkap penuh merupakan potensi masalah, sama halnya dengan kasus Rasyid Rajasa (anak dari Hatta Rajasa) yang menghilang entah bagaimana kelanjutannya.
  4. Banyaknya partai anggota Koalisi. Dengan begitu banyak partai yang bergabung dalam koalisi mendukung Prabowo, sangat beralasan jika nantinya terjadi politik bagi-bagi kekuasaan seperti yang terjadi pada masa pemerintahan SBY. Kita tentunya tidak ingin lagi memiliki menteri yang tidak kompeten di bidangnya.

Jokowi – JK

  1. Terlalu tunduk kepada Partai. Jokowi berkali-kali menyatakan tidak memikirkan tentang presiden, dan ingin fokus mengurus jakarta, tapi toh ia menyanggupi tawaran menjadi capres oleh PDIP. Bahkan Mega juga menekankan kalau Jokowi adalah petugas partai yang ditugaskan sebagai presiden.
  2. Menelan ludah sendiri. Baik Jokowi maupun JK sama-sama sudah mengingkari ucapan mereka sendiri. Jokowi menyatakan akan tetap menjadi gubernur jakarta selama 1 periode, namun toh ia menjadi capres ketika periodenya belum selesai. JK menyatakan jokowi belum siap menjadi presiden, namun toh ia menjadi cawapres dari Jokowi.
  3. Pencitraan yang berlebihan. Pada masa pilgub hingga pra-pencalonannya sebagai capres, media menampilkan jokowi sebagai manusia super. Bahkan ada berita tentang Jokowi kebelet buang air.

Analisa

Pada bagian ini saya mencoba menjustifikasi semua kekurangan pada masing-masing pasangan, mana yang lebih dapat saya tolerir kekurangannya. Kekurangannya akan saya bahas dari poin paling bawah, yaitu dari dari yang signifikan, ke faktor yang paling signifikan.

Saya mulai dari prabowo-hatta:

  1. Banyaknya partai anggota Koalisi. Tentu dengan banyaknya anggota koalisi dalam kubu Prabowo-Hatta, saya mengkhawatirkan terjadinya politik bagi-bagi kursi. Namun, toh di kubu Jokowi-JK tidak menutup kemungkinan juga akan melakukan politik bagi-bagi kursi. Sehingga poin kelemahan ini dapat saya tolerir.
  2. Potensial Masalah. Masa lalu prabowo terkait pelanggaran HAM, ditambah hubungannya dengan orde baru, membuat saya khawatir pemerintahannya kelak akan mengikuti gaya orde baru. Tapi ini juga hanya berupa kekhawatiran. Sangat memungkinkan jika Prabowo  sudah berubah menjadi orang yang lebih baik. Saya sendiri pernah mengalami masa kegelapan dalam hidup saya, tapi toh saya bisa berubah jadi lebih baik. Sehingga poin kelemahan ini dapat saya tolerir.
  3. Minim Prestasi. Prabowo adalah ketua umum HKTI (Himpunan Kerukunan Tani Indonesia) dan APPSI (Asosiasi Pedagang Pasar Seluruh Indonesia). Namun tidak ada terobosan berarti yang beliau lakukan, padahal posisinya sebagai ketua umum sangat memungkinkan dia untuk dapat menjalankan ide-ide nya untuk mensejahterakan petani dan pedagang.
  4. Mengeluarkan modal Besar untuk kampanye. Prabowo merupakan orang yang kaya, ia tercatat memiliki 27 perusahaan yang bergerak di berbagai sektor bisnis. Dengan hartanya yang berlimpah, ditambah posisinya sebagai ketua umum HKTI dan APPSI, sangat memungkinkan bagi dirinya untuk membuat terobosan dan gebrakan yang mensejahterakan petani dan pedagang. Tapi ia memilih untuk menggunakan hartanya sebagai modal kampanye.

Sementara dari Jokowi-JK :

  1. Pencitraan yang berlebihan. Berita di media terkait jokowi hingga hal yang sangat remeh membuat saya muak. Sehingga terkesan jokowi adalah figur artificial, yang dipoles oleh media. Tidak menutup kemungkinan kalau citra yang ditampilkan Jokowi berlebihan dan tidak sesuai dengan keadaan sebenarnya. Tapi fakta menunjukkan jika sebagian dari citra itu memang benar adanya. Adalah sebuah fakta bahwa Jokowi meraih lebih dari 90% suara di Solo, jauh sebelum beliau mengikuti pilgub Jakarta. Sebuah fakta yang menunjukkan jika beliau berhasil memuaskan konstituennya di Solo. Sehingga poin kelemahan ini dapat saya tolerir.
  2. Menelan ludah sendiri. Saya adalah orang yang sangat kecewa karena Jokowi mengkhianati janjinya memenuhi masa tugasnya di jakarta selama 1 periode. Harapan yang saya bawa adalah beliau tetap di Jakarta selama 5 tahun, barulah setelah itu menjadi capres pada tahun 2019. Saat itu saya sangat kecewa, dan melihat Jokowi sebagai boneka dari Megawati (saat ini pun saya masih melihat seperti itu). Akan tetapi ketika saya mencoba melihat di posisi beliau, dengan tekanan yang kuat dari partai, ditambah berbagai masalah di jakarta, ia memilih untuk meninggalkan jakarta.
  3. Terlalu tunduk kepada Partai. Poin ini sangat terkait dengan poin sebelumnya, dan merupakan kekurangan paling fatal dari Jokowi. Jokowi sangat patuh pada partai, dan dikhawatirkan menjadi presiden boneka. Saya sampai sekarang pun masih berpikir demikian. Tapi ketika saya melihat Bu Risma di Surabaya yang dengan berat hati ingin mundur dari jabatannya karena tidak kuat dengan tekanan partai, saya jadi dapat memahami bahwa posisi Jokowi mirip dengan Bu Risma.

Kesimpulan

Berdasarkan analisa kekurangan kedua capres-cawapres, kesimpulan saya adalah :

Jokowi memiliki niat untuk memperbaiki masyarakat, tapi ia belum tentu punya kemampuan untuk melaksanakannya. Prabowo memiliki kemampuan untuk memperbaiki masyarakat, tapi ia tidak memiliki niat untuk melaksanakannya.

Hasil pengamatan saya selama ini adalah, jika ada seseorang yang sesumbar menjanjikan berbagai program jika terpilih, tapi saat ini ia tidak melakukan fase-fase awal dari programnya, maka ia hanyalah mengumbar janji palsu.

Jika ia mau merubah Indonesia, dia bisa melakukannya tanpa status sebagai pejabat. Hal inilah yang membuat saya menjagokan Anies Baswedan, karena ia menggagas dan menjalankan Indonesia Mengajar, tanpa harus menjadi pejabat.

Pandangan pribadi saya adalah, menjadi pejabat akan memudahkan proses pelaksanaan, tetapi bukan syarat untuk melaksanakannya. Fungsinya sebagai scaling up, bukan prequisite.

Hal ini pula yang membuat saya menyamakan Harry Tanoe, ARB, dan Prabowo ke dalam satu kategori. Mereka bertiga memiliki kemampuan untuk memperbaiki Indonesia, tapi ketiganya memilih untuk menggunakan harta mereka untuk kampanye. Itulah mengapa saya menyatakan Prabowo memiliki kemampuan untuk mengubah, tapi ia menggunakan hartanya untuk kampanye presiden jauh-jauh hari, yang mana saya terjemahkan sebagai kurangnya niat. Dalam sudut pandang saya, seseorang tidak harus menjadi presiden untuk memperbaiki Indonesia.

Di sisi lain, Jokowi memiliki niat untuk memperbaiki masyarakat, terlihat dari track recordnya di Solo dan Jakarta. Walaupun memang banyak sekali kendala dan hambatan yang ada, hingga banyak program yang mandek. Tapi ia punya visi ke arah sana, walaupun belum tentu berhasil.

Jika menjadi presiden pun, ada kemungkinan Jokowi akan tersandera oleh partainya sendiri, atau oleh orang-orang di belakangnya. Tapi itu adalah bagian dari kendala dan hambatan yang harus ia tangani. Karena itulah saya menyatakan Jokowi memiliki niat untuk memperbaiki masyarakat, tapi belum tentu ia mampu melaksanakannya, karena sepanjang track recordnya, Jokowi belum berhasil melawan partai pendukungnya (PDIP) jika terjadi konflik kepentingan.

Maka pilihan pasangan less-evil menurut saya pribadi adalah Pasangan Jokowi-JK.

Penutup

Sebagai penutup, saya ingin mengajak semua orang untuk ikut berpartisipasi. Jangan menjadi orang yang diam dan mendiamkan. Lakukan analisa yang kritis terhadap kedua pasangan capres. Kemudian pilih yang menurut anda paling baik. Apakah anda mendukung Jokowi-JK atau Prabowo-Hatta tidak masalah. Selama anda menyadari penuh alasan kenapa anda memilih pasangan itu.

The only thing necessary for the triumph of evil is for good men to do nothing.
~Edmund Burke~

The Trickster #2 : The Lunch Bet

This is the second part of the short story. Read previous story here.

English version

A girl is working in front of her desk, when a guy comes to him.

Guy   : Hey Lily, lets eat. It’s already lunchtime.

Lily   : Hey Leo, you should go first. I almost finish my report.

Leo   : You seem to always have reason to reject me. Is that a financial report ?

Lily  : Yes. Why do you ask?

Leo  : Then I have a fun game for you. If you win, I will never ask to you have lunch with me. But if you lost, you must have lunch with me for a week. How about it?

Lily  : Depends on the game.

Leo  : Perfect. Because this is the game you can win. The game works like this : we take a data from your financial report, and if its first digit is below 5, I got 1 point. Otherwise, you got 1 point. With this, you have higher chance of winning, because I only got point if the digit is 1,2,3 or 4. While you get point if the digit are 5,6,7,8,9. We will take 100 sample data, and count all our point. You will have a 5/9 chance to win, and I only get 4/9. What do you think?

Lily : (Thinking briefly, and almost decided to accept the game, when a kid suddenly appear).

Kid : Don’t play that stupid game sis. He is trying to trick you.

Lily : Shiro, what are you doing here? Aren’t you supposed to be at school?

Shiro : That is not important. The important thing is that jerk want to trick you because he have huge advantage over you. And he is surely win it.

Lily : How is he have advantage over me? Wasn’t I got point for 5 digit, and he only got 4 digit?

Shiro : That is if the digit actually have same chane to appear. But in fact, many real-life data contain different distribution for first digit. Also known as Benford’s Law, which caused digit 1-4 appear far more often than the rest of digits.

Lily  : Wow. I don’t know that. How dare you do that to me ? (Lily looks at Leo with angry face).

Leo  : Err, I was joking. I guess I will go to lunch then. (Said Leo then run off).

Lily : Thank you Shiro, If you didn’t warn me he will successfully fool me. Anyway, why are you here?

Shiro : Your boss ask me to come to his office. He said it’s important.

Lily  : That’s strange. Anyway, his office is the last room  after the corner.

Shiro : Thanks.

 

Shiro walks towards the room, without realizing that something will happen to him.

To be continued …

 

Versi Bahasa Indonesia

The Trickster #1 : Guessing Box

This is a short story I wrote, due to the sudden idea I had in mind (Yes I’m impulsive, I know). This story is written in dual-language : English and Bahasa. Hope you enjoy it. And please help me improve it by editing its content, because my grammar is poor. I mean really poor.

The Trickster : English Version

A man walks with quick step. From opposite direction, a boy is running while holding 3 boxes. Due to his size, the boy’s sight is blocked by the boxes. Inevitably, the boy bumped the man and crashed down. The boy winced in pain while holding his leg.

Feeling sorry, the man approach the kid.

The Man   : I am sorry kid. Are you okay?

The Boy   : Do I look like okay? My leg is hurt, and I am supposed to bring back the box in time.

The Man   : I am truly sorry. Is there anything I can help you with?

The Boy   : Yes, you should pay me as compensation. Let see, because I will fail to deliver the box in time, I will lost my payment, and you should cover for it.

The Man   : Ah, its okay. How much is it? (The man checks out his wallet and give $5 to the kid). Is this enough?

The Boy   : Are you kidding me? You should pay me $50 for your mistake.

 The Man  : $50? That is ridiculous, and it is not my mistake in the first place. You are the one who running and bump me.

The Boy   : No. It is clearly your fault, because I deliver these boxes everyday, and never bump anyone before.

The Man  : Okay, how about another compensation. I will pay you $10, and talk to your boss.

The Boy  : No way. How about we decide it with a game. Because I have 3 empty boxes here, you will put $50 inside one of the box. You did it without my knowing. And then I will guess which box contains money. If my guess is correct, the money is mine. If it is wrong, the money is yours.

The Man  : (Thinking quickly and realize that the game is in fact in his favor). Okay that is a fair game. Lets do this.

The Boy  : Ah, because the boxes is mine and I know it better than you. I will put $20 inside it too, so the game is now fair for both of us.

The Man : (What a fool! He doesn’t even know he is at disadvantage). Seems fair for me.

The Boy  : Okay, Now I will turn my head back, and you put your money. (The Boy then turn his head back).

The Man  : Done. Now one of the boxes contains $70 money. Your turn.

The Boy : Let me think. Because each box have different color. The First box is Black, the second Box is Yellow, and the third  box is Blue. I am sure that the money is in either Black or Yellow Box,  because you wear black suits and yellow tie. But I am still not sure which one it is.

The Man  : Hahaha, you got me (Hahaha, he really is an idiot. He tries to choose the box based on my clothes.)

The Boy  : Wait a minute, is there something you hide for me Sir? Because I think you are cheating.

The Man  : I am not cheating. I’m just amazed how stupid you are. You don’t understand a simple Math, do you? Because there is 3 boxes, and only 1 correct box. My chance of winning is 2/3, while yours only 1/3. Which mean I already win this game before it even begin.

The Boy  :  Ahh, that makes sense. But now the game is not fair, and I want it to be fair. We should modify the rule. You must reveal one of the box that didn’t contain money. So now both of us have 1/2 chance to win.

The Man  : What ? You can’t change the rule after the game is played.

The Boy  : And you should tell me that math before we began. But you didn’t. So you are trying to dupe me, and you still call yourself a man. I only want to make the game fair for both of us.

The Man  : Allright. (The man is annoyed, but his pride as a man force him to play along). I reveal that the First Box (the black one) is empty. Now you have 50% chance to win and lose, the same as me.

The Boy  : So the black box is empty. So it means the money is inside the yellow box. But, because you are trying to make the game fair, I will appreaciate that. I will let you win. My choice is the Third Box, the blue one. And it is final.

The Man  : (A bit confused, the man reveal the third box, and it actually contains money inside it).

The Boy  : Wow. It seems that God agreed with me, that you should pay me. (The boy then happily take the money and walk off).

The Man is confused, angry, and amazed at the same time.

Meanwhile, the boy walk with a big grin on his face.  he then whispered to himself.

“I don’t understand Math he said. Hahaha, what a fool. Math actually proves that I already win the game before it even started. Another easy money for me today. Hahaha”.

Kuro

Inside a car, a mysterious man watch the boy. “That was his third victim for this week. So that was the kid my boss told me about.  Interesting. Let see what you do next, Kuro”.

To be continued …

==============================================================

The Trickster : Bahasa Indonesia

– Coming Soon-

Tutorial #19 : Optimizing Game Performance

Introduction

One of key element between a good game and a bad game is its performance. No matter how good your game is, if it performs badly (lagging, not-intuitive) it will be a bad game.

FPS & Frame Skip

A normal mobile game have a 25 FPS (Frame per Second). That means every 1 second, the game updates its condition and refresh screen display 25 times. The higher the FPS, the smoother it will looks like. For example : a video usually have 60FPS. However, in mobile game, 25 FPS is enough to deliver a good gaming experience.

Normally, the game will have 25 Frame per second. However, some time it might have lower FPS due to high process or rendering. When that happen, The Engine will try to have the same update per second, but skip some rendering process. This is because rendering an image requires more time than calculation process. How much frame can be skipped during lagging is defined as FrameSkip.

You can define both FPS and Frameskip when initiating the game in your Launcher. Higher FrameSkip will tolerate more lagging, but might make your screen less smooth.

Performance Statistic

When you develop the game, you will test the game in Emulator because it is simpler. However, emulator might not give the same result as when the game is played on actual device. Some Emulator runs so slow (like Nokia Emulator), others runs so smooth because they use up CPU resources (like Kemulator).

The only way to test whether the game actually performs well is by actually testing it on device. However, unlike Emulator you cannot use console to test the game. Inspedio Engine provide a way to test your game performance on actual device by showing Performance Statistic on device screen.

You can see the statictic on the bottom left of the screen. The statistic is displayed into 4 line :

  •  FPS         : This shows how much Update/Render/SkippedFrame on current second.
  • Process  : This shows how much time used by Update/Render process.
  • Sleep       : This shows how much sleeps time (unused time) on current second.
  • Time        : This simply shows how much second has elapsed.

Most time in the game is used for rendering graphics. More assets to render means more time to do the rendering process. When the game process took less time than it provided, the Engine will sleep the process to save battery and stabilize FPS. More sleep time means better performance.

You can disable Performance Statistic by setting InsGlobal.displayFPs to false.

Optimizing Performance

There are 4 usual reason why your game is lagging.

The first one is because you have too much object. More objects equals to more process, especially if you use collision detection on a large set of object. Inspedio Engine collision detection system is good enough for most game where the object count is less than 20. However if your game rely heavily on collision detection with large object (Like Touhou or other Shoot them up game), you should create your own collision detection system.

The second reason is because you use an heavy calculation process on your game. This is mostly done by using a large iteration, loop, or recursive process. For example when you create an AI for chess game, and you use exhaustive search algorithm. There are many ways to optimize this, for example is by storing pre-calculated value, or by using heuristic method.

The third reason for lagging is because you load asset (Image, Sound) during the game. Loading an image/sound will require certain amount of time, depends on how big the asset is. If your state use many assets, you should use Loading Screen during Screen transition, so that player will know that the game is still loading. Some game needs to load an asset during playing, for example an endless runner game with several environment stage. This can be handled by using InsHiddenLoader to load assets, by loading it using different thread (process), so it won’t affect game performance.

The fourth reason for lagging is because you render image outside of screen. Be warned that if you draw an asset outside of screen, it will still drawn, but cannot be seen by user. As a result, you just waste a good amount of processing time by drawing an object which won’t be visible. Inspedio Engine already handle this issue by checking whether the object have visible part on Screen before rendering them. An object is considered visible if any part of it is visible on screen (even only 1 pixel). However, if for some reason you have a very large asset (like World Map), you should split them into several part. Splitting a large asset and draw each pieces of it will prevents some pieces of it to not rendered if they currently are not visible on screen.

Conclusion

Optimizing a game is a tough process, and requires in-depth knowledge of the game mechanic. However you should not worry too much about it as Inspedio Engine already handle most of performance issue for you. As long as you use The engine properly and following tutorial guideline, you should do just fine.

Always remember the golden quote :

Premature optimization is the root of all evil.

Next Step : Optimizing Game Size.

Previous Step : Customize Pause Behavior.

Tutorial Index

Tutorial #18 : Customize Pause Behavior

Introduction

Pausing a Game is an essential feature for time-sensitive game, like action or real-time simulation. For Mobile game, pausing is even more important, because device event (such as receiving calls, message, or alarm) can interrupt your game. It is very important that you pause the game when it interrupted. Inspedio Engine provide 2 way to implement pause behavior in your game.

Global Pause

The first method for implementing pause behavior is by defining Global Pause Object. Global Pause object is a fixed object that doesn’t receive any event. The object can only show Pause notification (The Game is Paused. Touch/press to continue), and automatically resumed upon player input (touch at any position, or any keypad press). You however need to define what to show for each device type (Keypad and Touch). Global Pause object will automatically shown when game is interrupted, regardless of current game state.

You can define your Global Pause Object by extending InsPause class.

public class MyGlobalPause extends InsPause{

 public void showPause(InputType Input) {
  if(Input == InputType.TOUCH){
  // Show Pause notif for Touch Device

  } else if(Input == InputType.KEYPAD){
  // Show Pause notif for Keypad Device
  }
 }
}

Custom Pause

The second method is by using Custom Pause. This is useful if you want to show Pause Popup Menu when game is interrupted, and let user choose their action. For example, you want to show a popup menu which contain Resume, Restart, or Back button upon interruption.

To implement that behavior, you need to disable global pause, and implement your behavior inside pause() method on your state. Note that if you do this, the object on your state will not automatically paused. Which means you have to pause them manually. The better approach is by using a meta-group. Meta-group is a group object which used to contain all object with similar behavior. It works like folder and sub-folder.

The following example can give you a better understanding.

public class MyGameState extends InsState{

 InsGroup meta;

 public void create() {
  // create and add meta group.
  // Any game object to be paused must be added to meta, not state
  meta = new InsGroup();
  this.add(meta);
 }

 public void pause(){
  super.pause();
  // Make all object at meta group inactive (paused)
  meta.active = false;
 }

}

 

Next Step : Optimizing Game Performance.

Previous Step : Toying With Camera.

Tutorial Index

Tutorial #17 : Toying with Camera

Introduction

Camera is used in the game when the game environment is larger than the device screen size. Inspedio Engine provide a camera system which helps you explore the game world. It also have built-in autofollow feature, to automatically follow an object movement (usually player’s character).

Boundary

Before using Camera, you must first set the Boundary of Camera. Boundary means the limit of camera movement. For example, you want to limit Camera movement so it will never go out of Game World Area.

Camera is a sub-class of InsBasic, which means you can actually controls it by using action, (MoveTo, MoveBy), or manually setting its position.

Every sprite class have a built-in camera (only sprite, shape and text doesn’t have it). At default, all sprite will use Global Camera Object, which can be accessed at InsGlobal.camera.

AutoFollow

You can set your camera to automatically follow an object movement. The followed object will be put into the center of the screen, unless it goes to camera boundary. You can also place it not exactly on the center (say in the left-center for endless runner game) by setting Offset Value. The Offset will make the Camera place your object in spesific distance from center of the screen.

Usage

You can see an example of Camera Usage in SampleCameraState class.

public void setCamera(){
 // Get Global Camera Object
 InsCamera cam = InsGlobal.camera;

 // Set Camera Boundary
 cam.setBoundary(Left, Right, Top, Bottom);

 // Command Camera to Follow spesific object
 cam.follow(sprite);

}

Next Step : Customize Pause Behavior.

Previous Step : Saving Game Data.

Tutorial Index

Tutorial #16 : Saving Game Data

Introduction

One of essential aspect of the game is saving game data.  Game Data is the record of player’s progress of the game, for example : how much level he unlocked, his high score, or what equipment he currently owned.

Inspedio Engine provided a way to dynamically save your game data, and load them again when user plays the game next time.

Data Flow

Before explaining how Saving Game Data works, you must first understand the flow of data in the Engine.

SaveLoad

There are 3 type of Data you should be aware of.

  • Device Data      : This is where the data is stored on actual device. When a data is stored on device, it will stay there as long as user did not uninstall the game.
  • Program Data   : Data from your own game. This is what you want to store at device.
  • Engine Data     : Intermediary Data from your game to the device. You cannot explicitly use this in your game. This data is used as temporary data when storing data into device, or loading data from device.

The main purpose of Saving Game Data is storing your data from game (program) into user’s device, so you can load it again the next time user plays the game. You can do this by using Engine as your intermediary medium (and also make it easier).

The save/load mechanism works like this :

  1. When you want to save the game, you have to assign data from your game into the engine.
  2. And then you call save method. The engine will store your assigned data into device.
  3. When you want to load the data from device, you first call load method. The engine will load data from device.
  4. Then you retrieve the data from engine into your game.

Assign & Retrieve

Save and Load process are already handled by Engine. However, Assign & retrieve process must be defined for each game, because each game have different data to save. You can define this by creating your own Save class.

Create a class that extends InsSave, declare a constructor with your Game Name. Make Sure you use consistent name, as his name will be used to load your game back. If you update the game, do not change the Name, so it can load previous data.

Assigning data is simply adding new SaveDataObject by declaring its name and its value. The value can be everything from Integer, String, Boolean, Byte, and even Array.

Retrieving Data is checking whether data exist, and then assigning it to variable in your game. When retrieving data, you have to define its type. The type must match your variable type.

public class MyOwnSaveLoad extends InsSave{

 public static int _SCORE;

 public MyOwnSaveLoad() {
  super("MyGame");
 }

 public void assignData() {
  this.addData(new SaveDataObject("Score", _SCORE));
 }

 public void retrieveData() {
  if(isDataExist("Score")){_SCORE = this.getData("Score").GetDataInt();}
 }

}

Set As Default Save Class

Finally, you need to set your own save class as default SaveLoad. This can be done by using your own Save Class as default value during launcher init() method.

 


public class MyLauncher extends InsMain{

 protected void init() {
  this.init(new MyInitialState(), new MyOwnSaveLoad(), ScreenOrientation.PORTRAIT);
 }

}

 

Save & Load

After set up your own Custom Save Class, you can save the game whenever you want by calling save() method. You can also call load() method to load the game, but it is actually unneeded. The game automatically load saved data during initiating. And The Engine will automatically retrieve it for you.

You can then use the retrieved data (in previous sample, the program data is _SCORE).


InsGlobal.save.save();

 

Next Step : Toying with Camera.

Previous Step : Enhancing Game Loader.

Tutorial Index

Tutorial #15 : Enchancing Game Loader

Introduction

If you have played many games, you will be familiar with Loading Screen. But do you know what it actually does? Loading Screen is an intermediate screen, which displayed when next screen is not ready yet.

Some Game Screen requires some time to constructed, for example if that screen use a large image, or need to somehow generate large data (like randomized dungeon generator).

Load Progress

Inspedio Engine provide a way to manage your loading screen, and shows loading progress to user. You can use this by defining loading progress during state creation. This can be done by setting InsGlobal.loadProgress value progressively after each process in your state creation.

package game.state;

import com.inspedio.entity.InsState;
import com.inspedio.system.core.InsGlobal;

public class LoadState extends InsState{

 public void create() {
   // Do process 1 here
   InsGlobal.loadProgress = 25;

   // Do process 2 here
   InsGlobal.loadProgress = 50;

   // Do process 3 here
   InsGlobal.loadProgress = 75;

   // Do process 4 here
   InsGlobal.loadProgress = 100;
  }
}

Please note that Load progress must have value between 0-100.

Customize Loading Screen

You can customize Loading Screen by defining your own Loader State. This can be done by creating  a class which extends InsLoader. InsLoader is similar to InsState (because it is subclass of InsState). The difference is that you have to define state behavior when Loading progress changed.

A simple approach is by using InsProgressSprite (a sprite which can be drawn progressively) to represents current loading progress.


public class MyOwnLoader extends InsLoader{

 public void create() {
 // set up your loader visual here

 }

 public void progressChanged(int CurrentProgress) {
 // Define screen behavior when progress value changed

 } 

}

Set Default Loader

Finally, you need to set your own loader as default Loader. This can be done by using your own Loader State as default value during launcher init() method.


public class MyLauncher extends InsMain{

 protected void init() {
  this.init(new MyInitialState(), new MyOwnLoader(), ScreenOrientation.PORTRAIT);
 }

}

Next Step : Saving Game Data.

Previous Step : Playing Sound & Music

Tutorial Index

Tutorial #14 : Playing Sound and Music

Introduction

Music & Sound is important for game. It can enhance game experience, and makes it more fun. Inspedio Engine provide a way to manage your audio files.

Audio Format

J2ME platform supports 3 audio format : MIDI, AVI, and MP3. All of them can be used, but we strongly encourage you to only use MIDI format. The most crucial reason is filesize, as both MP3 and AVI file usually have large size.

A good J2ME game have less than 1 megabyte size, which already includes the whole program, image asset, audio asset, text (for level design or dialog). Some older device cannot even download file higher than 1 megabyte.

BGM & SFX

An audio file can be categorized into one of 2 type : BGM or SFX. A BGM or Background Music is a infinitely repeated music that played as background audio, usually last for 30-90 second. A SFX or Sound Effect is a one-time play audio effect, usually have very short duration, used to give special audio effect such as explosion, collision, etc.

You have to declare an audio file as BGM or SFX before playing them. Important note though : J2ME device only have 1 audio channel, which means you cannot play multiple audio at the same time. Only one of them can be played. So you have to choose between BGM or SFX in your game. You can work around this by using BGM in menu screen and then use SFX in play screen.

Usage

To play an audio, you have to load it first, and then play or stop it whenever you want. Remember that only one audio can be loaded at the time. You can play audio with following code :


public static void playBGM(){
// Load BGM files
InsGlobal.setAudio("/bgm.mid", AudioEncode.MIDI, AudioType.BGM);
 // Play Audio, or resume paused Audio
 InsGlobal.startAudio();
}

public static void playSFX(){
 // Load SFX files
 InsGlobal.setAudio("/sfx.mid", AudioEncode.MIDI, AudioType.SFX);
 // Play Audio, or resume paused Audio
 InsGlobal.startAudio();
}

public static void stopAudio(){
 // Pause or Stop Audio
 InsGlobal.stopAudio();
}

public static void resetAudio(){
 // Reset currently played audio
 InsGlobal.resetAudio();
}

Next Step : Enhancing Game Loader.

Previous Step : Detecting Collision.

Tutorial Index

Tutorial #13 : Detecting Collision

Introduction

Collision detection is a method to detect whether two object collided. Most games relies heavily on this as their core gameplay. Inspedio engine also provide a way to detect collision heavily. Collision detection in Inspedio Engine use the simplest implementation, which is by using Collision Box or Collision Sphere.

Collision Box Vs Sphere

There are many type of collision detection, but the simplest method are by using collision area (and also what we use in The Engine). Collision Area are geometrical shape that represent area of collision. An example of Collision Area is shown below :

Collision Area

The object on the left use Collision Box while the other use Collision Sphere. Notice that when using collision box, the collision area is larger than actual shape of sprite. On the other hand, using collision sphere, some part of sprite is not covered by collision area. Which type is better to use depends on the object itself.

Tolerance Value

The size of Collision Box and Collision Sphere are calculated from Sprite size. However, for some games, you might need to increase or decrease its size. You can easily do that by setting tolerance value.

Collision Tolerance

The above image shows how tolerance value affects Collision Area. The higher tolerance, the smaller collision area, thus requiring object to be more closer toward each other in order to collide. Tolerance can also used to enlarge collision area by setting its value to negative.

    • Blue Area     : Normal Collision Area
    • Green Area  : Collision Area with Tolerance Value = 10
    • Red Area      : Collision Area with Tolerance Value = -10

Collision Callback

To handle collision, you need a callback which will be executed when the collision happen. For example, if you have a bullet and a player object. When they collided, the player will lost some energy and the bullet destroyed. Please remember to destroy unused game object, to prevent memory leak and prevent game from lagging.

Usage

To handle collision, you need to create 2 group. The group contains a list of object that might collide with each other. You can create an object and add it into group during the game. For example : in shooting game a bullet hot by player can only collide with enemy object, but cannot collide with its own bullet. Then you register object group and collision callback into state.

You can add multiple collision event into state. However, keep in mind that too many object will make the game laggy, so make sure you clear/destroy unused game object (after collided or out of screen).

The sample code can be found at SampleCollisionState class.

 public void setCollision(){
 // Register Collision Event into State.
  this.addCollisionEvent("<NAME>", group1, group2, tolerance,
  CollisionType.SPHERE, new InsCollisionCallback() {
   public void call(InsBasic obj1, InsBasic obj2) {
   // Put Collision handler here
   }
  });
 }

Next Step : Playing Sound & Music

Previous Step : Handling User Input

Tutorial Index