andengine Sprite button should stay pressed - android

I've got a problem with Andengine
I didn't find a class for checkboxes or switches (on/off) in Andengine so I want to create a button which I can press and it will stay pressed.
I tried with mButtonSprite.State.PRESSED but I don't know how to use it, maybe you can help me...
My code:
public class MainActivity extends SimpleBaseGameActivity{
private int WIDTH = 1600;
private int HEIGHT = 900;
private BuildableBitmapTextureAtlas mBitmapTextureAtlas;
private ITiledTextureRegion mButtonTextureRegion;
public Sprite mButtonSprite;
private State mState;
#Override
public EngineOptions onCreateEngineOptions() {
final Camera mCamera = new Camera(0, 0, WIDTH, HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR,
new RatioResolutionPolicy(WIDTH, HEIGHT),
mCamera);
}
#Override
protected void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
mBitmapTextureAtlas = new BuildableBitmapTextureAtlas(mEngine.getTextureManager(),WIDTH, HEIGHT,TextureOptions.BILINEAR);
mButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(mBitmapTextureAtlas,this,"rectangle_one.png", 2,1);
try {
mBitmapTextureAtlas
.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(
0, 2, 1));
mBitmapTextureAtlas.load();
} catch (TextureAtlasBuilderException e) {
e.printStackTrace();
}
}
#Override
protected Scene onCreateScene()
{
this.mEngine.registerUpdateHandler(new FPSLogger(60));
final Scene mScene = new Scene();
mScene.getBackground().setColor(00000, 00000,00000);
mScene.setTouchAreaBindingOnActionDownEnabled(true);
ButtonSprite mButtonSprite = new ButtonSprite(900,450, mButtonTextureRegion,
mEngine.getVertexBufferObjectManager()){
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY){
return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
}
};
mScene.registerTouchArea(mButtonSprite);
mScene.attachChild(mButtonSprite);
return mScene;
}
}

Create sprite sheet of with two images say off and on (one row with 2 coloumns) .Then create an animates sprite like this
testsprite_music = new AnimatedSprite(0, 0,
resourcesManager.test_region_music, vbom) {
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
if (prefs.getBoolean("musiconoff", true)) {
// Log.e("The music is on im going to off ","The music is on im going to off ");
android.content.SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean( "musiconoff", false );
editor.commit();
testsprite_music.setCurrentTileIndex(0);
}
else
{// Log.e("The music is off im going to on ","The music is off im going to on ");
testsprite_music.setCurrentTileIndex(1);
android.content.SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean( "musiconoff", true );
editor.commit();
}
}
return true;
}
};

1. For CheckBox type:
if you want to enable and disable a button as check box use shared preference
For Example
boolean isChecked = getFromPreference();
if(isButtonEnbled)
{
// show checkSprite
}else{
// show unchecked Sprite
}
2.To show a button when pressed
in onTouchArea we have three options
if(ActionBegin){
// fadeIn
}else if(ActionEnd){
// fade out
}
In this way we have many alternatives

Related

FATAL EXCEPTION: Thread Android

I am trying to draw bullets on the screen when the player presses, but
after a few bullets I get the following error: FATAL EXCEPTION: Thread-2
Here is the classes of the bullet and of the gameView
public class Bullet {
private int x;
private int y;
private int speed;
private Bitmap bitmap;
public Bullet(Context context,int PositionX,int PositionY) {
Log.v("i am in bullet"," come on!!!");
speed = 10;
x = PositionX;
y = PositionY;
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.flash);
}
public void update() {
//Log.v("i am in update bullet"," come on!!!");
//animating the star horizontally right side
//by increasing x coordinate with player speed
x += 20;
}
public Bitmap getBitmap(){return bitmap;}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
returns
public class GameView extends SurfaceView implements Runnable {
private long fps;
private long timeThisFrame;
volatile boolean playing;
private Thread gameThread = null;
private Player player;
//a screenX holder
int screenX;
int i=0;
//context to be used in onTouchEvent to cause the activity transition from GameAvtivity to MainActivity.
Context context;
//the score holder
int score;
//the high Scores Holder
int highScore[] = new int[4];
//Shared Prefernces to store the High Scores
SharedPreferences sharedPreferences;
//to count the number of Misses
int countMisses;
//indicator that the enemy has just entered the game screen
boolean flag ;
//an indicator if the game is Over
private boolean isGameOver ;
private Paint paint;
private Canvas canvas;
private SurfaceHolder surfaceHolder;
private Enemy enemies;
//created a reference of the class Friend
private Friend friend;
//private Bullet bullet;
private ArrayList<Star> stars = new
ArrayList<Star>();
private ArrayList<Bullet> bullet = new
ArrayList<Bullet>();
//defining a boom object to display blast
private Boom boom;
//the mediaplayer objects to configure the background music
static MediaPlayer gameOnsound;
final MediaPlayer killedEnemysound;
final MediaPlayer gameOversound;
public GameView(Context context, int screenX, int screenY) {
super(context);
player = new Player(context, screenX, screenY);
surfaceHolder = getHolder();
paint = new Paint();
//initializing context
this.context = context;
int starNums = 20;
for (int i = 0; i < starNums; i++) {
Star s = new Star(context,screenX, screenY);
stars.add(s);
}
enemies = new Enemy(context,screenX,screenY);
//initializing boom object
boom = new Boom(context);
//initializing the Friend class object
friend = new Friend(context, screenX, screenY);
//setting the score to 0 initially
score = 0;
//setting the countMisses to 0 initially
countMisses = 0;
this.screenX = screenX;
isGameOver = false;
//initializing shared Preferences
sharedPreferences = context.getSharedPreferences("SHAR_PREF_NAME",Context.MODE_PRIVATE);
//initializing the array high scores with the previous values
highScore[0] = sharedPreferences.getInt("score1",0);
highScore[1] = sharedPreferences.getInt("score2",0);
highScore[2] = sharedPreferences.getInt("score3",0);
highScore[3] = sharedPreferences.getInt("score4",0);
//initializing the media players for the game sounds
gameOnsound = MediaPlayer.create(context,R.raw.gameon);
killedEnemysound = MediaPlayer.create(context,R.raw.killedenemy);
gameOversound = MediaPlayer.create(context,R.raw.gameover);
//starting the music to be played across the game
gameOnsound.start();
}
#Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
synchronized (surfaceHolder) {
update();
draw();
control();
}
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
private void update() {
//incrementing score as time passes
score++;
player.update();
//setting boom outside the screen
boom.setX(-250);
boom.setY(-250);
for (Star s : stars) {
s.update(player.getSpeed());
}
for (Bullet b : bullet) {
b.update();
}
//setting the flag true when the enemy just enters the screen
if(enemies.getX()==screenX){
flag = true;
}
enemies.update(player.getSpeed(),getFps());
}
private void draw() {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.argb(500,135,206,250));
paint.setColor(Color.WHITE);
paint.setTextSize(20);
for (Star s : stars) {
canvas.drawBitmap(
s.getBitmap(),
s.getX(),
s.getY(),
paint);
}
for (Bullet b : bullet) {
canvas.drawBitmap(
b.getBitmap(),
b.getX(),
b.getY(),
paint);
}
canvas.drawBitmap(
player.getBitmap(),
player.getX(),
player.getY(),
paint);
canvas.drawBitmap( enemies.getBitmap(), enemies.getframeToDraw(), enemies.getwhereToDraw(), null);
//drawing the score on the game screen
paint.setTextSize(30);
canvas.drawText("Score:"+score,100,50,paint);
//drawing boom image
canvas.drawBitmap(
boom.getBitmap(),
boom.getX(),
boom.getY(),
paint
);
//draw game Over when the game is over
if(isGameOver){
paint.setTextSize(150);
paint.setTextAlign(Paint.Align.CENTER);
int yPos=(int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2));
canvas.drawText("Game Over",canvas.getWidth()/2,yPos,paint);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
private void control() {
try {
gameThread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
gameThread.interrupt();
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
//stop the music on exit
public static void stopMusic(){
gameOnsound.stop();
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
player.stopBoosting();
break;
case MotionEvent.ACTION_DOWN:
player.setBoosting();
break;
}
//if touch the player
if (player.getDetectCollision().contains((int)motionEvent.getX(), (int)motionEvent.getY())) {
Bullet b = new Bullet(context,player.getX()+player.getDetectCollision().width()
,player.getY()-(player.getDetectCollision().height()/2));
bullet.add(b);
Log.d("test", "touch not inside myEditText");
}
//if the game's over, tappin on game Over screen sends you to MainActivity
if(isGameOver){
if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
context.startActivity(new Intent(context,MainActivity.class));
}
}
return true;
}
public long getFps(){
return fps;
}
}

Is this the right way to detect a touch on a rectangle in LibGdx ? Does not seem to be working for me

This is the code for my gamescreen where i want burst my ballon when its touched .
orientation is portrait.
but it does not seem to work for me.
public class GameScreen implements Screen {
final BB game;
private BitmapFont font;
private static final int no_of_frames = 2;
Texture ballonFrames;
TextureRegion[] burstFrames = new TextureRegion[no_of_frames];
Animation burstAnimation;
Array<Rectangle> ballons;
TextureRegion currentFrame;
long lastBallonTime;
int ballonBursted;
OrthographicCamera camera;
int ballonMissed;
Sound ballonBursting;
public GameScreen(final BB gam) {
this.game = gam;
ballonFrames = new Texture(Gdx.files.internal("ballon_burst.png"));
font = new BitmapFont(Gdx.files.internal("font.fnt"), false);
ballonBursting = Gdx.audio.newSound(Gdx.files
.internal("BallonBursting.wav"));
TextureRegion[][] tmp = TextureRegion.split(ballonFrames,
ballonFrames.getWidth() / 2, ballonFrames.getHeight());
burstFrames[0] = tmp[0][0];
burstFrames[1] = tmp[0][1];
burstAnimation = new Animation(3.0f, burstFrames);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
ballons = new Array<Rectangle>();
spawnBallon();
}
private void spawnBallon() {
Rectangle ballon = new Rectangle();
ballon.x = MathUtils.random(0, 800 - 64); //
ballon.y = 0;
ballon.width = 40;
ballon.height = 80;
ballons.add(ballon);
lastBallonTime = TimeUtils.nanoTime();
}
private boolean ballonBursted(Rectangle ballon) {
Vector2 touch = new Vector2(Gdx.input.getX(), Gdx.input.getY());
if (ballon.contains(touch))
return true;
else
return false;
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(0, 0, 0.3f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
InputProcessor processor;
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
font.draw(game.batch, "Ballon Bursted :" + ballonBursted, 0, 700);
font.draw(game.batch, "Ballon Missed:" + ballonMissed, 275, 700);
for (Rectangle ballon : ballons) {
game.batch.draw(burstFrames[0], ballon.x, ballon.y);
}
if (TimeUtils.nanoTime() - lastBallonTime > 1000000000) {
spawnBallon(); // a ballon every second
}
Iterator<Rectangle> iter = ballons.iterator();
while (iter.hasNext()) {
Rectangle ballon = iter.next();
ballon.y = ballon.y + 100 * Gdx.graphics.getDeltaTime();
if (ballonBursted(ballon) == true) {
ballonBursted++;
game.batch.draw(burstFrames[1], ballon.x, ballon.y);
ballonBursting.play();
iter.remove();
}
else if (ballon.y + 64 > 800) {
iter.remove();
ballonMissed++;
}
}
if (ballonMissed > 5) {
game.setScreen(new ScoreScreen(game, ballonBursted));
}
game.batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
ballonFrames.dispose();
ballonBursting.dispose();
game.batch.dispose();
}
I am using animation class of libgdx to change my image of ballon to the one where its bursted .
I am fairly new to libgdx and unable to figure out what wrong am i doing here .
Should i create a table and layout my ballon elements as actor?
Try something like this:
private boolean ballonBursted(Rectangle ballon) {
Vector3 touchPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
if (ballon.contains(touchPos.x, touchPos.y))
return true;
else
return false;
}
please read this https://stackoverflow.com/a/18555705/2158970
If I understand it right you just want to know if the touchpoint is contained in the Rectangle ballon. Then you could use Rectangle#contains() method:
ballon.contains(Gdx.input.getX(), Gdx.input.getY());
see also the source code of Rectangle class

TMX file is not shown properly using AndEngine

I have written a position locator application for indoor positioning. I've used TMX files to render my floor maps and load them with AndEngine. The problem is that the program does not show the TMX file properly.
Here is the original file:
and here is what my application shows:
How can I fix this? Here is code:
public class TiledViewer extends SimpleBaseGameActivity implements
IOnSceneTouchListener, IScrollDetectorListener,
IPinchZoomDetectorListener {
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
private SmoothCamera camera;
private TMXTiledMap mTMXTiledMap;
private SurfaceScrollDetector mScrollDetector;
private PinchZoomDetector mPinchZoomDetector;
private float mPinchZoomStartedCameraZoomFactor;
#Override
public EngineOptions onCreateEngineOptions() {
this.camera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 400,
400, 10f);
final CroppedResolutionPolicy canvasSurface = new CroppedResolutionPolicy(
CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.PORTRAIT_FIXED, canvasSurface, this.camera);
if (MultiTouch.isSupported(this)) {
if (MultiTouch.isSupportedDistinct(this)) {
Toast.makeText(
this,
"MultiTouch detected --> Both controls will work properly!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
this,
"MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(
this,
"Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.",
Toast.LENGTH_LONG).show();
}
return engineOptions;
}
#Override
public void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setOnAreaTouchTraversalFrontToBack();
this.mScrollDetector = new SurfaceScrollDetector(this);
this.mPinchZoomDetector = new PinchZoomDetector(this);
scene.setOnSceneTouchListener(this);
scene.setTouchAreaBindingOnActionDownEnabled(true);
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(), TextureOptions.DEFAULT,
this.getVertexBufferObjectManager(),
new ITMXTilePropertiesListener() {
#Override
public void onTMXTileWithPropertiesCreated(
final TMXTiledMap pTMXTiledMap,
final TMXLayer pTMXLayer,
final TMXTile pTMXTile,
final TMXProperties<TMXTileProperty> pTMXTileProperties) {
}
});
this.mTMXTiledMap = tmxLoader.loadFromAsset("tmx/m03.tmx");
} catch (final TMXLoadException e) {
Debug.e(e);
}
final TMXLayer tmxLayer = this.mTMXTiledMap.getTMXLayers().get(0);
scene.attachChild(tmxLayer);
this.camera.setBounds(0, 0, tmxLayer.getHeight(), tmxLayer.getWidth());
this.camera.setBoundsEnabled(true);
return scene;
}
#Override
public void onScrollStarted(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onScroll(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onScrollFinished(final ScrollDetector pScollDetector,
final int pPointerID, final float pDistanceX, final float pDistanceY) {
final float zoomFactor = this.camera.getZoomFactor();
this.camera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY
/ zoomFactor);
}
#Override
public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent) {
this.mPinchZoomStartedCameraZoomFactor = this.camera.getZoomFactor();
}
#Override
public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent, final float pZoomFactor) {
this.camera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor
* pZoomFactor);
}
#Override
public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector,
final TouchEvent pTouchEvent, final float pZoomFactor) {
this.camera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor
* pZoomFactor);
}
#Override
public boolean onSceneTouchEvent(final Scene pScene,
final TouchEvent pSceneTouchEvent) {
this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);
if (this.mPinchZoomDetector.isZooming()) {
this.mScrollDetector.setEnabled(false);
} else {
if (pSceneTouchEvent.isActionDown()) {
this.mScrollDetector.setEnabled(true);
}
this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
}
return true;
}
}
I had the same problem for realize an indoor program.
I found a way to make better the display by editing directly the .tmx file.
In the tileset you should add those attributes spacing and margin.
For example:
tileset spacing="3" margin="2"
If you put the good value in the diferent field, you should have a better display.
My problem was resolved just by adding a margin=10 in this tileset.
I hope that help you,

Is it possible to use AndEngine with SherlockActivity?

I'm a noob to Android development and i want to develop a game you using AndEngine and use SherlockActionBar for navigation. The problem is that AndEngine requires me to extend SimpleBaseGameActivity and SherlockActionBar needs to extend SherlockActivity. I am attempting to use a nested class approach, but i can't figure out how to make AndEngine initialize during OnCreate. Any help is greatly appreciated.
--EDIT--
I've tinkered with the static attachment demo in the ActionBarSherlock examples, but still can't figure out how to make this work, since there is no OnCreate method in the existing AndEngine demo code.
public class WABActivity extends SimpleBaseGameActivity implements IOnMenuItemClickListener, OnCreateOptionsMenuListener {
ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
protected static final int MENU_RESET = 0;
protected static final int MENU_QUIT = MENU_RESET + 1;
private Camera mCamera;
protected Scene mMainScene;
private BitmapTextureAtlas mBitmapTextureAtlas;
private ITextureRegion mFaceTextureRegion;
private Font mFont;
protected MenuScene mMenuScene;
#Override
public EngineOptions onCreateEngineOptions() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera);
}
#Override
public void onCreateResources() {
FontFactory.setAssetBasePath("font/");
final ITexture fontTexture = new BitmapTextureAtlas(this.getTextureManager(), 256, 256, TextureOptions.BILINEAR);
this.mFont = FontFactory.createFromAsset(this.getFontManager(), fontTexture, this.getAssets(), "Plok.ttf", 48, true, android.graphics.Color.WHITE);
this.mFont.load();
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0);
this.mBitmapTextureAtlas.load();
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mMenuScene = this.createMenuScene();
/* Just a simple scene with an animated face flying around. */
this.mMainScene = new Scene();
this.mMainScene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));
final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion, this.getVertexBufferObjectManager());
face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight()));
this.mMainScene.attachChild(face);
setTheme(R.style.Theme_Sherlock); //<--Not sure if this goes here
mSherlock.setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW); //<--Not sure if this goes here
mSherlock.setContentView(???); //<--How do I set ContentView? Do I need to set contentview?
return this.mMainScene;
}
#Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
if(this.mMainScene.hasChildScene()) {
/* Remove the menu and reset it. */
this.mMenuScene.back();
} else {
/* Attach the menu. */
this.mMainScene.setChildScene(this.mMenuScene, false, true, true);
}
return true;
} else {
return super.onKeyDown(pKeyCode, pEvent);
}
}
#Override
public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
switch(pMenuItem.getID()) {
case MENU_RESET:
/* Restart the animation. */
this.mMainScene.reset();
/* Remove the menu and reset it. */
this.mMainScene.clearChildScene();
this.mMenuScene.reset();
return true;
case MENU_QUIT:
/* End Activity. */
this.finish();
return true;
default:
return false;
}
}
protected MenuScene createMenuScene() {
final MenuScene menuScene = new MenuScene(this.mCamera);
final IMenuItem resetMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_RESET, this.mFont, "RESET", this.getVertexBufferObjectManager()), new Color(1,0,0), new Color(0,0,0));
resetMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
menuScene.addMenuItem(resetMenuItem);
final IMenuItem quitMenuItem = new ColorMenuItemDecorator(new TextMenuItem(MENU_QUIT, this.mFont, "QUIT", this.getVertexBufferObjectManager()), new Color(1,0,0), new Color(0,0,0));
quitMenuItem.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
menuScene.addMenuItem(quitMenuItem);
menuScene.buildAnimations();
menuScene.setBackgroundEnabled(false);
menuScene.setOnMenuItemClickListener(this);
return menuScene;
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
return mSherlock.dispatchCreateOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
sub = menu.addSubMenu("Options");
sub.add(0, 1, 0, "Settings");
sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override //<-- Giving Error: must override or implement a supertype method
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home || item.getItemId() == 0) {
return false;
}
if(item.getItemId()==1){
//SETTINGS SCREEN//
sub.removeItem(1);
sub.removeItem(2);
sub.removeItem(3);
sub.removeItem(4);
sub.removeItem(5);
sub.add(0, 5, 0, "Home");
sub.add(0, 2, 0, "High Scores");
sub.add(0, 3, 0, "Help");
sub.add(0, 4, 0, "About");
//mMode = startActionMode(new AnActionModeOfEpicProportions());
}
}
}
Look at the static attachment example included in the ActionBarSherlock demo code.
Static attachment exists exactly for this purpose.

Start animation with AndEngine Live Wallpaper extansion

I have code like this:
public class SnowFallService extends BaseLiveWallpaperService implements IOnAreaTouchListener{
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 800;
private ArrayList<Sprite> allSnow = new ArrayList<Sprite>();
// ===========================================================
// Fields
// ===========================================================
private ScreenOrientation screenOrientation;
private static TextureRegion snowTexture;
private static TextureRegion backgroundTexture;
private static Textures texture = null;
private Scene mScene;
public org.anddev.andengine.engine.Engine onLoadEngine() {
return new org.anddev.andengine.engine.Engine(new EngineOptions(true, this.screenOrientation, new FillResolutionPolicy(), new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT)));
}
public void onLoadResources() {
texture = new Textures(this, getEngine());
}
public void onUnloadResources() {
}
public Scene onLoadScene() {
final Scene mScene = new Scene();
backgroundTexture = texture.getBackground();
mScene.attachChild(new Sprite(0, 0, backgroundTexture));
snowTexture = texture.getSnowTextureRegion();
mScene.registerUpdateHandler(new IUpdateHandler() {
private long lastRaindropAdd = 0;
#Override
public void onUpdate(final float pSecondsElapsed) {
int size = allSnow.size();
int tmpInt = 0;
Random randGen = new Random();
for (int i = 0; i < size; i++) {
if (allSnow.get(i) != null){
Sprite snow = allSnow.get(i);
tmpInt = randGen.nextInt(4);
snow.setPosition(snow.getX() + (randGen.nextInt(5) - randGen.nextInt(5)) * randGen.nextInt(3), snow.getY() + tmpInt);
if (snow.getY() > CAMERA_HEIGHT || snow.getX() > CAMERA_WIDTH) {
synchronized(snow) {
size--;
allSnow.remove(i);
mScene.detachChild(snow);
}
}
}
}
tmpInt = randGen.nextInt(5000);
if (System.currentTimeMillis() - lastRaindropAdd > tmpInt) {
lastRaindropAdd = System.currentTimeMillis();
tmpInt = randGen.nextInt(CAMERA_WIDTH);
Sprite snow = getRaindrop(tmpInt, 0);
allSnow.add(snow);
mScene.attachChild(snow);
}
}
#Override
public void reset() {
}
});
return mScene;
}
public void onLoadComplete() {
// TODO Auto-generated method stub
}
public void onPauseGame() {
// TODO Auto-generated method stub
}
public void onResumeGame() {
// TODO Auto-generated method stub
}
public Sprite getRaindrop(float x, float y) {
return (new Sprite(x, y, snowTexture.deepCopy()));
}
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent,ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if(pSceneTouchEvent.isActionDown()) {
// HERE I WANT PLACE CODE, THAT WILL START ANIMATION.
return true;
}
return false;
}
}
So how to start animation on click? I want to make something like small cartoon.
In your onLoadScene method after registering update handler disable it.
mUpdateHandler.setEnabled(false);
And in onAreaTouched method enable it.
mUpdateHandler.setEnabled(true);
Btw I think it's not good practice to create Random instance every time in onUpdate method.
Here Josh describes how to override onTouch method (andEngine does not handle touch events for livewallpaper correctly, so you have to do it on your own). In few words, all you have to do is to override following function in BaseWallpaperGLEngine class (class is a part of andEngine live wallpaper extension:
#Override
public void onTouchEvent (MotionEvent event)
{
}

Categories

Resources