Android Tutorial GameView - Create 2D Android games - Part I

For new games it is recommended to use libGDX. See these tutorials:
How to make games
[URL='http://www.b4x.com/android/forum/threads/32592']Introduction to the libGDX library
[/URL]


GameView is a view that allows you to draw hardware accelerated graphics. Compared to software accelerated graphics, hardware accelerated graphics are many times faster. Using hardware accelerated graphics it is possible to create smooth, real-time games.

Note that the acceleration method used by GameView is only available from Android 3.0 and above. This also means that you need to reference android.jar from platform 11 or above (under Tools -> Configure paths).

You should add this line to the manifest editor:
B4X:
SetApplicationAttribute(android:hardwareAccelerated, "true")

It is important to understand how GameView works.

GameView holds a list of BitmapData objects. Each BitmapData object holds a reference to a bitmap and some parameters that tell GameView how to draw it.

When GameView redraws itself, it goes over the list of BitmapData objects and draws each one of them. The important thing about GameView is that the drawings are hardware accelerated.

In order to make GameView redraw itself you should call GameView.Invalidate.

BitmapData

Each BitmapData object represents a bitmap (or sprite) that will be drawn when GameView redraws itself.
BitmapData properties are:
  • Bitmap - The bitmap that will be drawn.
  • DestRect - A rectangle that defines the location and size of the drawn bitmap. For example to move a sprite you change DestRect values.
  • SrcRect - A rectangle that defines the bitmap's region that will be drawn. You can pass an uninitialized rectangle if you want to draw the complete bitmap. SrcRect can be useful for drawing a sprite from a sprite sheet, or to create scrolling effects.
  • Delete - A boolean value. When set to True, GameView will remove this BitmapData from the list during the next drawing (the bitmap will not be drawn).
  • Rotate - Number of degrees to rotate the bitmap.
  • Flip - Flips the bitmap based on one of the FLIP constants.

Typical game structure

Usually your game should consist of a single main timer. All the movements and the logic should happen in this timer's tick event. Eventually you call GameView.Invalidate. This will cause GameView to redraw itself after your code execution completes.

Simple bouncing smiley with a scrolling background

SS-2012-07-31_15.58.32.png


The attached project is a simple example with two BitmapData objects. One is the background and the other is the moving smiley. The background is scrolling to the left each tick. This is done by playing with SrcRect values so each part of the wide background image is draw each time.

The smiley DestRect is modified every tick to make it move.

The second part of this tutorial with a working "Asteroids" game is available here: http://www.b4x.com/forum/basic4andr...gameview-create-2d-android-games-part-ii.html

SS-2012-07-31_16.12.12.png


Another example (jumping smiley): http://www.b4x.com/forum/basic4andr...ngsmiley-gameview-example-iii.html#post151177

SS-2013-02-07_18.17.28.png
 

Attachments

  • GameViewSmiley.zip
    9.4 KB · Views: 5,156
Last edited:

bluejay

Active Member
Licensed User
Longtime User
Erel,

This project references a library called 'gameview'. Where to find this library?

bluejay
 

bluejay

Active Member
Licensed User
Longtime User
Ok found it in library threads - not sure how I missed it the first time.

bluejay
 

MiniDemonic

Member
Licensed User
Longtime User
Cool, I am going to play around with this, experiment on a runescape game of mine.


B4X:
>>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
CheckJNI is OFF


Calling main entry com.android.commands.pm.Pm
No content provider found for permission revoke: file:///data/local/tmp/GameViewSmiley_DEBUG.apk
No content provider found for permission revoke: file:///data/local/tmp/GameViewSmiley_DEBUG.apk
Removing non-system package:anywheresoftware.b4a.samples.gameviewsmiley
Force stopping package anywheresoftware.b4a.samples.gameviewsmiley uid=10046
Running dexopt on: anywheresoftware.b4a.samples.gameviewsmiley
Package anywheresoftware.b4a.samples.gameviewsmiley codePath changed from /data/app/anywheresoftware.b4a.samples.gameviewsmiley-2.apk to /data/app/anywheresoftware.b4a.samples.gameviewsmiley-1.apk; Retaining data and using new
DexOpt: load 107ms, verify+opt 324ms
Force stopping package anywheresoftware.b4a.samples.gameviewsmiley uid=10046
Code path for pkg : anywheresoftware.b4a.samples.gameviewsmiley changing from /data/app/anywheresoftware.b4a.samples.gameviewsmiley-2.apk to /data/app/anywheresoftware.b4a.samples.gameviewsmiley-1.apk
Resource path for pkg : anywheresoftware.b4a.samples.gameviewsmiley changing from /data/app/anywheresoftware.b4a.samples.gameviewsmiley-2.apk to /data/app/anywheresoftware.b4a.samples.gameviewsmiley-1.apk
New package installed in /data/app/anywheresoftware.b4a.samples.gameviewsmiley-1.apk
Force stopping package anywheresoftware.b4a.samples.gameviewsmiley uid=10046
generateServicesMap(android.accounts.AccountAuthenticator): 3 services unchanged
generateServicesMap(android.content.SyncAdapter): 10 services unchanged
Received broadcast Intent { act=android.intent.action.PACKAGE_REMOVED dat=package:anywheresoftware.b4a.samples.gameviewsmiley flg=0x10000010 (has extras) }
generateServicesMap(android.accounts.AccountAuthenticator): 3 services unchanged
generateServicesMap(android.content.SyncAdapter): 10 services unchanged
Received broadcast Intent { act=android.intent.action.PACKAGE_ADDED dat=package:anywheresoftware.b4a.samples.gameviewsmiley flg=0x10000010 (has extras) }
updatePackageParticipantsLocked: #1
Handling replaced theme package: anywheresoftware.b4a.samples.gameviewsmiley
Received broadcast Intent { act=android.intent.action.PACKAGE_REPLACED dat=package:anywheresoftware.b4a.samples.gameviewsmiley flg=0x10000010 (has extras) }
updatePackageParticipantsLocked: #1
GC_EXPLICIT freed 1441K, 39% free 13311K/21703K, paused 10ms+22ms
Shutting down VM
NOTE: attach of thread 'Binder Thread #3' failed
GC_CONCURRENT freed 98K, 83% free 455K/2560K, paused 1ms+3ms

>>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
CheckJNI is OFF
Calling main entry com.android.commands.am.Am
START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=anywheresoftware.b4a.samples.gameviewsmiley/.main} from pid 7393
Shutting down VM
NOTE: attach of thread 'Binder Thread #3' failed
GC_CONCURRENT freed 100K, 82% free 486K/2560K, paused 1ms+1ms
Start proc anywheresoftware.b4a.samples.gameviewsmiley for activity anywheresoftware.b4a.samples.gameviewsmiley/.main: pid=7404 uid=10046 gids={3003}
Turning on JNI app bug workarounds for target SDK version 4...
Reconfiguring input devices.  changes=0x00000004
Device reconfigured: id=6, name='synaptics-rmi-touchscreen', surface size is now 480x800, mode is 1
Config changed: {1.0 240mcc7mnc en_GB layoutdir=0 sw320dp w533dp h294dp nrml long land finger -keyb/v/h -nav/h s.61 themeResource=null}
Flushing caches (mode 0)
Flushing caches (mode 0)
GC_EXPLICIT freed 38K, 75% free 2177K/8387K, paused 4ms+34ms
GC_EXPLICIT freed <1K, 75% free 2177K/8387K, paused 4ms+5ms


Sending signal. PID: 7404 SIG: 3


threadid=3: reacting to signal 3
GC_EXPLICIT freed <1K, 75% free 2177K/8387K, paused 4ms+45ms


Wrote stack traces to '/data/anr/traces.txt'


loaded /system/lib/egl/libGLES_android.so


loaded /system/lib/egl/libEGL_adreno200.so


loaded /system/lib/egl/libGLESv1_CM_adreno200.so
loaded /system/lib/egl/libGLESv2_adreno200.so


setLightsOn(true)


Enabling debug mode 0


Sending signal. PID: 7404 SIG: 3


threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'


Flushing caches (mode 1)


showStatusIcon on inactive InputConnection


Displayed anywheresoftware.b4a.samples.gameviewsmiley/.main: +1s476ms


** Activity (main) Create, isFirst = true **


Could not find method anywheresoftware.b4a.BA.raiseEventFromUI, referenced from method anywheresoftware.b4a.objects.GameViewWrapper$1.onTouch


VFY: unable to resolve virtual method 512: Lanywheresoftware/b4a/BA;.raiseEventFromUI (Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;)V
VFY: replacing opcode 0x6e at 0x0041
** Activity (main) Resume **


Flushing caches (mode 0)
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@411ad9f8


GC_EXPLICIT freed 1422K, 39% free 13239K/21703K, paused 23ms+41ms


Shutting down VM


threadid=1: thread exiting with uncaught exception (group=0x40a4a1f8)


FATAL EXCEPTION: main
java.lang.NoSuchMethodError: anywheresoftware.b4a.BA.raiseEventFromUI
   at anywheresoftware.b4a.objects.GameViewWrapper$1.onTouch(GameViewWrapper.java:49)
   at android.view.View.dispatchTouchEvent(View.java:5536)
   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1684)
   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1684)
   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1684)
   at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1957)
   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1684)
   at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1912)
   at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1371)
   at android.app.Activity.dispatchTouchEvent(Activity.java:2364)
   at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1860)
   at android.view.View.dispatchPointerEvent(View.java:5721)
   at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:2890)
   at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2466)
   at android.view.ViewRootImpl.processInputEvents(ViewRootImpl.java:845)
   at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2475)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4575)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
   at dalvik.system.NativeStart.main(Native Method)
  Force finishing activity anywheresoftware.b4a.samples.gameviewsmiley/.main
Activity pause timeout for ActivityRecord{41121b38 anywheresoftware.b4a.samples.gameviewsmiley/.main}


Sending signal. PID: 7404 SIG: 3


threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'


Reconfiguring input devices.  changes=0x00000004


Device reconfigured: id=6, name='synaptics-rmi-touchscreen', surface size is now 480x800, mode is 1


Config changed: {1.0 240mcc7mnc en_GB layoutdir=0 sw320dp w320dp h508dp nrml long port finger -keyb/v/h -nav/h s.62 themeResource=null}


Dropped event because the current application is not responding and the user has started interacting with a different application.


Dropped event because the current application is not responding and the user has started interacting with a different application.
Sending signal. PID: 7404 SIG: 9


WIN DEATH: Window{41199b68 anywheresoftware.b4a.samples.gameviewsmiley/anywheresoftware.b4a.samples.gameviewsmiley.main paused=false}


Process anywheresoftware.b4a.samples.gameviewsmiley (pid 7404) has died.


WIN DEATH: Window{40e14e58 anywheresoftware.b4a.samples.gameviewsmiley/anywheresoftware.b4a.samples.gameviewsmiley.main paused=false}
GC_EXPLICIT freed 225K, 39% free 13259K/21703K, paused 20ms+18ms


[1] 5.onFinished: Installation state replication succeeded.


Activity destroy timeout for ActivityRecord{41121b38 anywheresoftware.b4a.samples.gameviewsmiley/.main}
 
Last edited:

Ricky D

Well-Known Member
Licensed User
Longtime User
Erel,

I'm using B4A 2.02 and get this when I try to compile

B4X:
Compiling code.                         0.05
Compiling layouts code.                 0.00
Generating R file.                      Error
AndroidManifest.xml:17: error: No resource identifier found for attribute 'hardwareAccelerated' in package 'android'

What do I need to do to get this working?

I have a Samsung Galaxy S2 running Android 4.0.3

regards, Ricky
 

Tom Christman

Active Member
Licensed User
Longtime User
Did you do the following accpording to Erel's post?

You should add this line to the manifest editor:
Code:

SetApplicationAttribute(android:hardwareAccelerated, "true")
 

Ricky D

Well-Known Member
Licensed User
Longtime User
Yes, that's in the manifest. It was there from the start.

regards, Ricky
 

wheretheidivides

Active Member
Licensed User
Longtime User
"You should add this line to the manifest editor:"
SetApplicationAttribute(android:hardwareAccelerate d, "true")

and what's the manifest editor again?
 

wheretheidivides

Active Member
Licensed User
Longtime User
...................................
1) copy code "SetApplicationAttribute(android:hardwareAccelerate d, "true")"
2) Open b4a
3) click on 'project' and then 'manifest editor' from the drop drown menu
4) paste code at the bottom screen
5) close window to save
 
Last edited:

Vabzboy

Member
Licensed User
Longtime User
Collision

I'm looking to create a similar game but with more than one ball.
How would I be able to collide these balls so they rebound off each other?

Thankyou
 

Pietervdbmag

New Member
Licensed User
Longtime User
in v2.22 I am getting:

Compiling code. 0.07
Compiling layouts code. 0.02
Generating R file. 0.29
Compiling generated Java code. 1.15
Convert byte code - optimized dex. 0.89
Packaging files. 0.37
Copying libraries resources 0.03
Signing package file (debug key). 0.65
ZipAlign file. 0.08
Installing file to device. 0.97
Installing with B4A-Bridge.
Installation will fail if the signing key is different than the previous used key.
In that case you will need to manually uninstall the existing application.

Completed successfully.
Code editor is in read-only mode during debugging.
Press Debug - Stop (or on the Stop button at the bottom) to stop the debugger.

All other samples work though.. Anyone has got a solution?
 

aloof

Member
Licensed User
Longtime User
Really good, but beyond my capability.... i wish i could make games.... for me to learn this i would need every line commented on
 
Top