Moving a sprite with the accelerometer sensor

  ... tutorials on how to use AndEngine.

Moving a sprite with the accelerometer sensor

Postby BillyGalbreath » Mon Nov 29, 2010 5:37 am

I've been playing with this AndEngine stuff for about 2 days now, and I got to say I'm really impressed with it! These tutorials are really helping me get a good grasp on what is capable, and I figured I'd add my own, since I did not find anything on the subject and figured I'd help someone someday that reads this.

This simply moves a simple sprite on the screen by tilting your device in the direction you want it to go. Nothing fancy at all, and it can very probably be implemented a better way (if anyone has any pointers for me, I'm all ears ;))

Enough talk, I'll just paste the entire .java file here for ya'll to pick apart :p

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.pl3x.test.movesprite;
  2.  
  3. import org.anddev.andengine.engine.Engine;
  4. import org.anddev.andengine.engine.camera.Camera;
  5. import org.anddev.andengine.engine.handler.IUpdateHandler;
  6. import org.anddev.andengine.engine.options.EngineOptions;
  7. import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
  8. import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
  9. import org.anddev.andengine.entity.scene.Scene;
  10. import org.anddev.andengine.entity.scene.background.ColorBackground;
  11. import org.anddev.andengine.entity.sprite.Sprite;
  12. import org.anddev.andengine.entity.util.FPSLogger;
  13. import org.anddev.andengine.opengl.texture.Texture;
  14. import org.anddev.andengine.opengl.texture.TextureOptions;
  15. import org.anddev.andengine.opengl.texture.region.TextureRegion;
  16. import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
  17. import org.anddev.andengine.ui.activity.BaseGameActivity;
  18.  
  19. import android.hardware.Sensor;
  20. import android.hardware.SensorEvent;
  21. import android.hardware.SensorEventListener;
  22. import android.hardware.SensorManager;
  23.  
  24. public class MoveSprite extends BaseGameActivity implements SensorEventListener {
  25.  
  26.     // ===========================================================
  27.     // Constants
  28.     // ===========================================================
  29.  
  30.     private static final int CAMERA_WIDTH = 720;
  31.     private static final int CAMERA_HEIGHT = 480;
  32.  
  33.     // ===========================================================
  34.     // Fields
  35.     // ===========================================================
  36.  
  37.     private Sprite sprite;
  38.     private Camera mCamera;
  39.     private Texture mTexture;
  40.     private TextureRegion mSpriteTextureRegion;
  41.     private SensorManager sensorManager;
  42.  
  43.     private int accellerometerSpeedX;
  44.     private int accellerometerSpeedY;
  45.     private int sX, sY; // Sprite coordinates
  46.  
  47.     // ===========================================================
  48.     // Constructors
  49.     // ===========================================================
  50.  
  51.     // ===========================================================
  52.     // Getter & Setter
  53.     // ===========================================================
  54.  
  55.     // ===========================================================
  56.     // Methods for/from SuperClass/Interfaces
  57.     // ===========================================================
  58.  
  59.     public Engine onLoadEngine() {
  60.         this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  61.         return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
  62.     }
  63.  
  64.     public void onLoadResources() {
  65.         this.mTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
  66.         this.mSpriteTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/face_box.png", 0, 0);
  67.  
  68.         this.mEngine.getTextureManager().loadTexture(this.mTexture);
  69.     }
  70.  
  71.     @SuppressWarnings("static-access")
  72.     public Scene onLoadScene() {
  73.         sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
  74.         sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);
  75.  
  76.         this.mEngine.registerUpdateHandler(new FPSLogger());
  77.         this.mEngine.registerUpdateHandler(new IUpdateHandler() {
  78.             public void onUpdate(float pSecondsElapsed) {
  79.                 updateSpritePosition();
  80.             }
  81.  
  82.             public void reset() {
  83.                 // TODO Auto-generated method stub
  84.             }
  85.         });
  86.  
  87.         final Scene scene = new Scene(1);
  88.         scene.setBackground(new ColorBackground(0.2f, 0.3f, 0.4f));
  89.  
  90.         sX = (CAMERA_WIDTH - this.mSpriteTextureRegion.getWidth()) / 2;
  91.         sY = (CAMERA_HEIGHT - this.mSpriteTextureRegion.getHeight()) / 2;
  92.  
  93.         sprite = new Sprite(sX, sY, this.mSpriteTextureRegion);
  94.         sprite.setScale(1);
  95.         scene.getTopLayer().addEntity(sprite);
  96.  
  97.         return scene;
  98.     }
  99.  
  100.     public void onLoadComplete() {
  101.  
  102.     }
  103.  
  104.     public void onSensorChanged(SensorEvent event) {
  105.         synchronized (this) {
  106.             switch (event.sensor.getType()) {
  107.                 case Sensor.TYPE_ACCELEROMETER:
  108.                     accellerometerSpeedX = (int)event.values[1];
  109.                     accellerometerSpeedY = (int)event.values[0];
  110.                     break;
  111.             }
  112.         }
  113.     }
  114.     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  115.         //
  116.     }
  117.  
  118.     // ===========================================================
  119.     // Methods
  120.     // ===========================================================
  121.  
  122.     private void updateSpritePosition() {
  123.         if ((accellerometerSpeedX != 0) || (accellerometerSpeedY != 0)) {
  124.             // Set the Boundary limits
  125.             int tL = 0;
  126.             int lL = 0;
  127.             int rL = CAMERA_WIDTH - (int)sprite.getWidth();
  128.             int bL = CAMERA_HEIGHT - (int)sprite.getHeight();
  129.  
  130.             // Calculate New X,Y Coordinates within Limits
  131.             if (sX >= lL) sX += accellerometerSpeedX; else sX = lL;
  132.             if (sX <= rL) sX += accellerometerSpeedX; else sX = rL;
  133.             if (sY >= tL) sY += accellerometerSpeedY; else sY = tL;
  134.             if (sY <= bL) sY += accellerometerSpeedY; else sY = bL;
  135.  
  136.             // Double Check That New X,Y Coordinates are within Limits
  137.             if (sX < lL)      sX = lL;
  138.             else if (sX > rL) sX = rL;
  139.             if (sY < tL)      sY = tL;
  140.             else if (sY > bL) sY = bL;
  141.  
  142.             sprite.setPosition(sX, sY);
  143.         }
  144.     }
  145.  
  146.     // ===========================================================
  147.     // Inner and Anonymous Classes
  148.     // ===========================================================    
  149. }
Parsed in 0.023 seconds, using GeSHi 1.0.8.4
BillyGalbreath
 
Posts: 7
Joined: Mon Nov 29, 2010 5:32 am

Re: Moving a sprite with the accelerometer sensor

Postby Stylisoft » Wed Dec 01, 2010 11:53 pm

Thanks! :)
Very useful for a beginner like me to discover quickly the basis of how declaring/moving a sprite on the screen (it completes the andengine examples).
Stylisoft
 
Posts: 2
Joined: Sun Nov 28, 2010 11:07 am

Re: Moving a sprite with the accelerometer sensor

Postby czyang » Tue Jan 18, 2011 4:21 pm

Thanks !!
Change the two variables to float can make sensor more sensitive.

private int accellerometerSpeedX;
private int accellerometerSpeedY;

private float accellerometerSpeedX;
private float accellerometerSpeedY;
My app website: http://codeand.me.
My Andengine Game:
EggMan Jump: http://codeand.me/archives/408
Magic Tiles: http://codeand.me/archives/305
AhahPah — voice control game!: http://codeand.me/archives/505
czyang
 
Posts: 37
Joined: Sat Nov 20, 2010 5:24 pm

Re: Moving a sprite with the accelerometer sensor

Postby squeeb » Sat Jun 11, 2011 9:54 pm

I am wondering if there is a way to use this and add joints to the equation? sprite that doesnt move, attached to other sprites that are attached to each other that also move with accelerometer?
anyone able to do this?
squeeb
 
Posts: 168
Joined: Mon May 16, 2011 1:24 am

Re: Moving a sprite with the accelerometer sensor

Postby methodin » Sun Jun 12, 2011 8:22 pm

Is this different from the one in the PhysicsExample?
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. @Override
  2.         public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) {
  3.                 final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getY(), pAccelerometerData.getX());
  4.                 this.mPhysicsWorld.setGravity(gravity);
  5.                 Vector2Pool.recycle(gravity);
  6.         }
  7.  
Parsed in 0.011 seconds, using GeSHi 1.0.8.4
Check out my FREE game Particly
http://particly.com
methodin
 
Posts: 52
Joined: Wed Apr 20, 2011 3:07 am

Re: Moving a sprite with the accelerometer sensor

Postby Coder_For_Life22 » Thu Nov 24, 2011 5:37 pm

This is really great! Really great work. it definitely completes the angengine examples.

Also if you want to make the Sprite more sensative or move fast you can multiply the accellerometerspeedX and Y by a number to make it more sensative like i do below in the UpdateSpritePosition() method.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. // Calculate New X,Y Coordinates within Limits
  2.                     if (sX >= lL) sX += accellerometerSpeedX*3; else sX = lL;
  3.                     if (sX <= rL) sX += accellerometerSpeedX*3; else sX = rL;
  4.                     if (sY >= tL) sY += accellerometerSpeedY; else sY = tL;
  5.                     if (sY <= bL) sY += accellerometerSpeedY; else sY = bL;
Parsed in 0.011 seconds, using GeSHi 1.0.8.4


Enjoy!
User avatar
Coder_For_Life22
 
Posts: 1036
Joined: Wed Nov 09, 2011 5:37 pm

Re: Moving a sprite with the accelerometer sensor

Postby gose » Tue Jan 10, 2012 12:32 pm

thanks, your tutorial is very useful for me, now I have problems with setting up the tilt angle control, please help me :(
gose
 
Posts: 1
Joined: Tue Jan 10, 2012 12:22 pm

Re: Moving a sprite with the accelerometer sensor

Postby axeltrance » Fri Jan 13, 2012 3:12 pm

have a bit of error on this:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. this.mTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
  2.         this.mSpriteTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/face_box.png", 0, 0);
  3.  
Parsed in 0.012 seconds, using GeSHi 1.0.8.4



Cannot instantiate the type Texture.
The method createFromAsset(Texture, DefaultActivity, String, int, int) is undefined for the type TextureRegionFactory.
and

Syntax: [ Download ] [ Hide ]
  1. scene.getTopLayer().addEntity(sprite); 


The method getTopLayer() is undefined for the type Scene
axeltrance
 
Posts: 2
Joined: Fri Jan 13, 2012 2:55 pm

Re: Moving a sprite with the accelerometer sensor

Postby Ice » Fri Jan 13, 2012 5:27 pm

its writed by old date andengine
old -
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. scene.getTopLayer().addEntity(sprite);
Parsed in 0.011 seconds, using GeSHi 1.0.8.4

new -
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. scene.attachChild(Sprite)
Parsed in 0.012 seconds, using GeSHi 1.0.8.4


Old
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. this.mTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
  2.  
  3.         this.mSpriteTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/face_box.png", 0, 0);
Parsed in 0.012 seconds, using GeSHi 1.0.8.4

New
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. this.mTexture = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
  2.  
  3.         this.mSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mTexture, this, "gfx/face_box.png", 0, 0);
Parsed in 0.014 seconds, using GeSHi 1.0.8.4


something like that, if you have question you can PM me, or post it here.
Ice
 
Posts: 11
Joined: Thu Dec 01, 2011 2:17 pm

Re: Moving a sprite with the accelerometer sensor

Postby sir-lewis » Sun Jan 15, 2012 5:51 pm

I've been having a problem regarding the accelerometer lately, maybe someone here can help.
Im using similar code in my game in which I am moving a sprite by the accelerometer, how would I go about writing the current position of the sprite to the screen, (its x,y and z values) and having them update automatically with the movement of the sprite?
sir-lewis
 
Posts: 11
Joined: Wed Nov 16, 2011 5:59 pm

Next

Return to Tutorials

Who is online

Users browsing this forum: Google Feedfetcher and 19 guests