So we are going to cover the following:
1. Basic creation of a Sprite.
2. Attaching a Listener to a Sprite/Object so it can be updated
3. Handling Touch Input with regards to Sprites
So, lets get started. First, you will want to create a new Sprite. So, make sure you have your Texture and Texture Region setup properly, and then create the following function in your class:
Using java Syntax Highlighting
- private void createSprite()
- {
- final Sprite sprite = new Sprite(100, 100, mYourSpritesTextureRegion);
- this.mEngine.getScene().getTopLayer().addEntity(sprite);
- }
Parsed in 0.029 seconds, using GeSHi 1.0.8.4
Remember to change the mYourSpritesTextureRegion Texture Region to the one you are using for your Sprite!
Once you have done this, call this method from your onLoadScene() method, and test out the application. You should see a Sprite on your screen at X=100 and Y=100.
Now, we want to be able to do something with this Sprite. So, lets make it's position update when we Touch and Drag the Sprite!
We are going to have to edit the createSprite() method so that it creates a listener for the Sprite, which will be called when we touch it. Here is the updated code:
Using java Syntax Highlighting
- private void createSprite()
- {
- final Scene scene = this.mEngine.getScene();
- final Sprite sprite = new Sprite(100, 100, mYourSpritesTextureRegion)
- {
- @Override
- public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
- float pTouchAreaLocalX, float pTouchAreaLocalY)
- {
- }
- };
- scene.registerTouchArea(sprite);
- scene.getTopLayer().addEntity(sprite);
- }
Parsed in 0.031 seconds, using GeSHi 1.0.8.4
What we have done, is added an IOnAreaTouchedListener to the Sprite, and registered this within the Scene. So now when we touch the Sprite, the onAreaTouched() method will be called, and we can handle our Sprite updating within there.
So, to make the Sprite follow your finger when you have touched it, add the following code into the Sprites onAreaTouched() method:
Using java Syntax Highlighting
- sprite.setPosition(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
Parsed in 0.033 seconds, using GeSHi 1.0.8.4
If you were to run this code now, the results would look a little weird, as the Sprites position is being allocated with regards to its top left corner. So update the code to the following:
Using java Syntax Highlighting
- sprite.setPosition(pSceneTouchEvent.getX() - this.getWidth()/2, pSceneTouchEvent.getY() - this.getHeight()/2);
Parsed in 0.035 seconds, using GeSHi 1.0.8.4
Run the code again, and you should now be able to touch and drag your Sprites around your screen!!!
Hope this helps some people out, I know some people are a little confused as to how to updated a Sprites location etc, so this should help out.
