I'm using this to create a player body
private void addPlayer(){
// viral -- add player
final float startX = (CAMERA_WIDTH - this.mPlayerTextureRegion
.getWidth()) / 2;
final float startY = CAMERA_HEIGHT + 100;
this.playerFace = new Sprite(startX, startY, this.mPlayerTextureRegion,
this.getVertexBufferObjectManager());
this.playerBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld,
playerFace, BodyType.DynamicBody, FIXTURE_DEF);
final PhysicsHandler physicsHandler = new PhysicsHandler(playerFace);
playerFace.registerUpdateHandler(physicsHandler);
playerBody.setBullet(true);
playerFaceHalfWidth = playerFace.getWidth() / 2;
playerFaceHalfHeight = playerFace.getHeight() / 2;
this.mScene.attachChild(playerFace);
playerFace.setY(CAMERA_HEIGHT - playerFaceHalfHeight * 2);
}
This is how I'm detecting collision with other sprites:
protected void onManagedUpdate(float pSecondsElapsed) {
if (playerFace.collidesWith(this)) {
// safe of touching border - else game over
if (!isPlayerInSafeZone()) {
Log.w("cd", "Game Over");
isGameInProgress = false;
mScene.setIgnoreUpdate(true);
processLevelEnd();
}
}
};
The issue now is that even though i've added a circle body, the collision is detected with the player when the other sprites touch the corner of the png for player. it is a transparent area and the image has only a circle in it for which the body was created. Why is this happening? What is wrong in the above code?
::Update based on Lucaz's inputs:
This is my contactlistener
private ContactListener createContactListener()
{
ContactListener contactListener = new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
final Fixture x1 = contact.getFixtureA();
final Fixture x2 = contact.getFixtureB();
final String x1id = (String) x1.getBody().getUserData();
final String x2id = (String) x2.getBody().getUserData();
Log.w("cd", "x1 = " + x1id + " --- x2 = " + x2id);
}
#Override
public void endContact(Contact contact)
{
}
#Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
};
return contactListener;
}
This is how I'm setting the user data for the player and other sprites:
Player:
this.playerFace = new Sprite(startX, startY, this.mPlayerTextureRegion,
this.getVertexBufferObjectManager());
this.playerBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld,
playerFace, BodyType.DynamicBody, FIXTURE_DEF);
playerBody.setBullet(true);
playerBody.setUserData("player");
other sprites (balls):
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face,
BodyType.DynamicBody, FIXTURE_DEF);
body.setLinearVelocity(vector2);
body.setBullet(true);
body.setUserData("ball");
This is how i added the listener to physics world
this.mPhysicsWorld.setContactListener(createContactListener());
The listener is written to print the user data for colliding objects:
but when a sprite collides with player i get null for the player but user data for the other sprite as shown below... how to fix this?
x1 = null --- x2 = ball
its because collidesWith() method is checking collisions of sprites, and not bodies. So it checks if two sprites overlap (even if they are png images, they will stll be treated as not transparent rectangles). To check collisions between bodies there is another way:
private ContactListener createContactListener()
{
ContactListener contactListener = new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
final Fixture x1 = contact.getFixtureA();
final Fixture x2 = contact.getFixtureB();
}
#Override
public void endContact(Contact contact)
{
}
#Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
};
return contactListener;
}
Please look this simple tutorial:
http://www.matim-dev.com/handling-collisions-between-bodies.html
Related
I have load levels in my game. But it shows some errors in
registerEntityLoader and Loadlevelfromasset". I think it is missing in library files. I used both Andengines 2.0 and anchor center as libraries.
But shows errors like this
The method registerEntityLoader(new EntityLoader(){}) is undefined for the type SimpleLevelLoader
The method loadLevelFromAsset(AssetManager, String) is undefined for the type SimpleLevelLoader
Here my code is
private void loadLevel(int levelID)
{
final SimpleLevelLoader levelLoader = new SimpleLevelLoader(vbom);
final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.01f, 0.5f);
levelLoader.registerEntityLoader(new EntityLoader<SimpleLevelEntityLoaderData>(LevelConstants.TAG_LEVEL)
{
public IEntity onLoadEntity(final String pEntityName, final IEntity pParent, final Attributes pAttributes, final SimpleLevelEntityLoaderData pSimpleLevelEntityLoaderData) throws IOException
{
final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_WIDTH);
final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_HEIGHT);
// TODO later we will specify camera BOUNDS and create invisible walls
// on the beginning and on the end of the level.
return GameScene.this;
}
});
levelLoader.registerEntityLoader(new EntityLoader<SimpleLevelEntityLoaderData>(TAG_ENTITY)
{
public IEntity onLoadEntity(final String pEntityName, final IEntity pParent, final Attributes pAttributes, final SimpleLevelEntityLoaderData pSimpleLevelEntityLoaderData) throws IOException
{
final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X);
final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y);
final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE);
final Sprite levelObject;
if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM1))
{
levelObject = new Sprite(x, y, resourcesManager.platform1_region, vbom);
PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF).setUserData("platform1");
}
else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM2))
{
levelObject = new Sprite(x, y, resourcesManager.platform2_region, vbom);
final Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
body.setUserData("platform2");
physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));
}
else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_PLATFORM3))
{
levelObject = new Sprite(x, y, resourcesManager.platform3_region, vbom);
final Body body = PhysicsFactory.createBoxBody(physicsWorld, levelObject, BodyType.StaticBody, FIXTURE_DEF);
body.setUserData("platform3");
physicsWorld.registerPhysicsConnector(new PhysicsConnector(levelObject, body, true, false));
}
else if (type.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_COIN))
{
levelObject = new Sprite(x, y, resourcesManager.coin_region, vbom)
{
#Override
protected void onManagedUpdate(float pSecondsElapsed)
{
super.onManagedUpdate(pSecondsElapsed);
/**
* TODO
* we will later check if player collide with this (coin)
* and if it does, we will increase score and hide coin
* it will be completed in next articles (after creating player code)
*/
}
};
levelObject.registerEntityModifier(new LoopEntityModifier(new ScaleModifier(1, 1, 1.3f)));
}
else
{
throw new IllegalArgumentException();
}
levelObject.setCullingEnabled(true);
return levelObject;
}
});
levelLoader.loadLevelFromAsset(activity.getAssets(), "level/" + levelID + ".lvl");
}
I used latest version of Anchor. Help me to solve......
I tried almost everything but nothing works.
If you run it you will see a square falling down very slow.
I'm a beginner so explain it not too complicated.
Any questions about this code dylan.missu#gmail.com
Here is my code:
#Override
public void show() {
camera = new OrthographicCamera();
debugRenderer = new Box2DDebugRenderer();
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(100,100);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(Gdx.graphics.getHeight()/6,Gdx.graphics.getHeight()/6);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;
fixtureDef.restitution = 2;
Fixture fixture = body.createFixture(fixtureDef);
}
private void line(float X, float Y, float w, float h)
{
BodyDef bodyDef = new BodyDef();
bodyDef.type=BodyDef.BodyType.StaticBody;
bodyDef.position.set(X,Y);
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(w,h);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.restitution=0.4f;
fixtureDef.friction=0.5f;
Body theFloor=world.createBody(bodyDef);
theFloor.createFixture(fixtureDef);
}
private void wall(float A)
{
// is there a better way of doing this?
line(0,Gdx.graphics.getHeight()/2-A,Gdx.graphics.getWidth()/2-A,0);
line(Gdx.graphics.getWidth()/2-A,0,0,Gdx.graphics.getHeight()/2-A);
line(0,-Gdx.graphics.getHeight()/2+A,Gdx.graphics.getWidth()/2-A,0);
line(-Gdx.graphics.getWidth()/2+A,0,0,Gdx.graphics.getHeight()/2-A);
}
#Override
public void render(float delta) {
world.step(1 / 5f, 6, 2);
OrthographicCamera camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
processAccelerometer();
wall(1);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
debugRenderer.render(world, camera.combined);
}
#Override
public void dispose() {
world.dispose();
debugRenderer.dispose();
}
private void processAccelerometer() {
float y = Gdx.input.getAccelerometerY();
float x = Gdx.input.getAccelerometerX();
if (prevAccelX != x || prevAccelY != y) {
world.setGravity(new Vector2(y, -x));
prevAccelX = x;
prevAccelY = y;
}
}
#Override
public void hide()
{
// TODO: Implement this method
}
#Override
public void resize(int p1, int p2)
{
// TODO: Implement this method
}
#Override
public void resume()
{
// TODO: Implement this method
}
#Override
public void pause()
{
// TODO: Implement this method
}
#Override
public void render()
{
// TODO: Implement this method
}
}
In Box2D you have to take into account that 1 pixel = 1 meter. So, basically, everything you simulate in Box2D will be HUGE by default. And Box2D simulations are not accurate for huge distances, huge masses, huge speeds...
So all you have to do is convert your viewport with a conversion factor, so you'll just look at small entities, that will be easier to simulate.
For example, let's say you want 100 pixel = 1 meter, you'll put that code when you create your game screen :
WORLD_TO_BOX = 1/100f;
BOX_TO_WORLD = 1/WORLD_TO_BOX;
//Creation of the camera with your factor 100
camera = new OrthographicCamera();
camera.viewportHeight = Gdx.graphics.getHeight() * WORLD_TO_BOX;
camera.viewportWidth = Gdx.graphics.getWidth() * WORLD_TO_BOX;
camera.position.set(camera.viewportWidth/2, camera.viewportHeight/2, 0f);
camera.update();
Then, you'll create your boxes in term of camera.viewportWidth and camera.viewportHeight, instead of Gdx.graphics.getWidth() and Gdx.graphics.getHeight()
I your case you'll have :
PolygonShape shape = new PolygonShape();
shape.setAsBox(camera.viewportHeight/6,camera.viewportHeight/6);
You can see in my code, there is also a BOX_TO_WORLD conversion factor. It will be used when you want to render graphics over your box2D bodies.
For that, look at the answer of this question.
I want to control the box by 2 fingers like below:
I have basic MouseJoint implementation:
public class MyMouseJoint{
OrthographicCamera cam;
World world;
Body groundBody ;
public MouseJoint mouseJoint = null;
Body hitBody = null;
Vector2 target = new Vector2();
Vector3 testPoint = new Vector3();
QueryCallback callback = new QueryCallback() {
#Override
public boolean reportFixture (Fixture fixture) {
// if the hit fixture's body is the ground body we ignore it
if (fixture.getBody() == groundBody) return true;
// if the hit point is inside the fixture of the body
// we report it
if (fixture.testPoint(testPoint.x, testPoint.y)) {
hitBody = fixture.getBody();
return false;
} else
return true;
}
};
public MyMouseJoint(OrthographicCamera cam, World world, Body groundBody){
this.cam=cam;
this.world=world;
this.groundBody = groundBody;
}
//USE THIS FUNCTION IN touchDown
public void createMouseJoint(float x, float y){
// translate the mouse coordinates to world coordinates
testPoint.set(x, y, 0);
cam.unproject(testPoint);
// ask the world which bodies are within the given
// bounding box around the mouse pointer
hitBody = null;
world.QueryAABB(callback, testPoint.x - 0.1f, testPoint.y - 0.1f, testPoint.x + 0.1f, testPoint.y + 0.1f);
if (hitBody != null) {
MouseJointDef def = new MouseJointDef();
def.bodyA = groundBody;
def.bodyB = hitBody;
def.collideConnected = true;
def.target.set(testPoint.x, testPoint.y);
def.maxForce = 10000.0f * hitBody.getMass();
def.frequencyHz=100;
def.dampingRatio=0;
mouseJoint = (MouseJoint)world.createJoint(def);
hitBody.setAwake(true);
}
}
//USE THIS FUNCTION IN touchDragged
public void dragMouseJoint(float x, float y){
if (mouseJoint != null) {
cam.unproject(testPoint.set(x, y, 0));
mouseJoint.setTarget(target.set(testPoint.x, testPoint.y));
}
}
//USE THIS FUNCTION IN touchUp
public void releaseMouseJoint(){
if (mouseJoint != null) {
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
}
}
How can modify this class for using 2 fingers?
What you can do is create an array of Body and initialize hitbody[] with the pointer of your touch. you can change the above code to following code.
In the following function the varable pointer is the pointer if your current touch
public class MyMouseJoint{
OrthographicCamera cam;
World world;
Body groundBody ;
public MouseJoint mouseJoint[] = new MouseJoint[2];
Body hitBody[] = new Body[2];
Vector2 target = new Vector2();
Vector3 testPoint = new Vector3();
Body tempBody;
QueryCallback callback = new QueryCallback() {
#Override
public boolean reportFixture (Fixture fixture) {
// if the hit fixture's body is the ground body we ignore it
if (fixture.getBody() == groundBody) return true;
// if the hit point is inside the fixture of the body
// we report it
if (fixture.testPoint(testPoint.x, testPoint.y)) {
tempBody = fixture.getBody();
return false;
} else
return true;
}
};
public MyMouseJoint(OrthographicCamera cam, World world, Body groundBody){
this.cam=cam;
this.world=world;
this.groundBody = groundBody;
}
//USE THIS FUNCTION IN touchDown
public void createMouseJoint(float x, float y,int pointer){
// translate the mouse coordinates to world coordinates
testPoint.set(x, y, 0);
cam.unproject(testPoint);
// ask the world which bodies are within the given
// bounding box around the mouse pointer
hitBody[pointer] = null;
world.QueryAABB(callback, testPoint.x - 0.1f, testPoint.y - 0.1f, testPoint.x + 0.1f, testPoint.y + 0.1f);
hitBody[pointer] = tempBody;
if (hitBody[pointer] != null) {
MouseJointDef def = new MouseJointDef();
def.bodyA = groundBody;
def.bodyB = hitBody[pointer];
def.collideConnected = true;
def.target.set(testPoint.x, testPoint.y);
def.maxForce = 10000.0f * hitBody[pointer].getMass();
def.frequencyHz=100;
def.dampingRatio=0;
mouseJoint[pointer] = (MouseJoint)world.createJoint(def);
hitBody[pointer].setAwake(true);
}
}
//USE THIS FUNCTION IN touchDragged
public void dragMouseJoint(float x, float y,int pointer){
if (mouseJoint[pointer] != null) {
cam.unproject(testPoint.set(x, y, 0));
mouseJoint[pointer].setTarget(target.set(testPoint.x, testPoint.y));
}
}
//USE THIS FUNCTION IN touchUp
public void releaseMouseJoint(int pointer){
if (mouseJoint[pointer] != null) {
world.destroyJoint(mouseJoint[pointer]);
mouseJoint[pointer] = null;
}
}
}
Please help! My game crash after remove Joint with collides.
The game is the body that is hanging on the rope. Finger cut the rope, and the game crashes!
My code:
#Override
protected Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mScene = new Scene();
this.mScene.setBackground(new Background(0, 0, 0));
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
/* Create the face and add it to the scene. */
ball = new Sprite(200, 50, this.mBallTextureRegion, this.getVertexBufferObjectManager());
ball.setScale(0.5f);
final Rectangle point = new Rectangle(400, 0, 5, 5, this.getVertexBufferObjectManager());
rope = new Line(point.getX()+5/2, point.getY()+5/2, ball.getX(), ball.getY(), this.getVertexBufferObjectManager());
this.mScene.attachChild(ball);
this.mScene.attachChild(rope);
this.mScene.attachChild(point);
final Body ballBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.DynamicBody, FIXTURE_DEF);
final Body pointBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, point, BodyType.StaticBody, FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ball, ballBody, true, true) {
#Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
final Vector2 movingBodyWorldCenter = ballBody.getWorldCenter();
rope.setPosition(rope.getX1(), rope.getY1(), movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
}
});
final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
revoluteJointDef.initialize(pointBody, ballBody, pointBody.getWorldCenter());
revoluteJointDef.enableMotor = true;
revoluteJointDef.maxMotorTorque = 1;
final Joint joint = this.mPhysicsWorld.createJoint(revoluteJointDef);
//collide detector
this.mScene.registerUpdateHandler(new IUpdateHandler() {
#Override
public void reset() { }
#Override
public void onUpdate(final float pSecondsElapsed) {
if(rope.collidesWith(cutLine)) {
mPhysicsWorld.destroyJoint(joint);
mScene.detachChild(rope);
}
}
});
this.mScene.registerUpdateHandler(this.mPhysicsWorld);
this.mScene.setOnSceneTouchListener(this);
return this.mScene;
}
#Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()) {
this.addCuter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
if(pSceneTouchEvent.isActionMove()) {
this.moveCuter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
if(pSceneTouchEvent.isActionUp()) {
this.delCuter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
return false;}
private void addCuter(final float pX, final float pY) {
cutBegin = new Rectangle(pX, pY, 5, 5, this.getVertexBufferObjectManager());
cutEnd = new Rectangle(pX, pY, 5, 5, this.getVertexBufferObjectManager());
cutLine = new Line(cutBegin.getX()+5/2, cutBegin.getY()+5/2, cutEnd.getX(), cutEnd.getY(), this.getVertexBufferObjectManager());
this.mScene.attachChild(cutBegin);
this.mScene.attachChild(cutEnd);
this.mScene.attachChild(cutLine);
cutEnd.setColor(1, 0, 0);
cutLine.setColor(1, 0, 0);}
private void moveCuter(final float pX, final float pY) {
cutEnd.setPosition(pX-5/2, pY-5/2);
cutLine.setPosition(cutBegin.getX()+5/2, cutBegin.getY()+5/2, pX, pY); }
private void delCuter(final float pX, final float pY) {
this.mScene.detachChild(cutBegin);
this.mScene.detachChild(cutEnd);
this.mScene.detachChild(cutLine);}
Error LogCat
03-14 10:45:48.329: A/libc(12926): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1)
I find that this usually occurs when you try to alter some aspect in the game which the update is dependant on from an event firing, i.e., outside of an,
mActivity.runOnUpdateThread(new Runnable()
{
#Override
public void run()
{
//...
}
});
Your onSceneTouchEvent looks like it may be a likely contender! Try adding the above code around the function calls which make changes to the scene to make it 'safe', i.e., you are not altering game variables from an interrupt while they are being processed by the update thread.
I am new with AndEngine. I just created a scene with many spawned sprites that come from above screen height in landscape mode. Now I want to remove a sprite when I touch on it. Problem is, when I touched the screen the most recent sprite is removed and I can't remove the tapped sprite individually.
Here is my code:
//======== TimerHandler for collision detection and cleaning up ======
IUpdateHandler detect = new IUpdateHandler() {
#Override
public void reset() {
}
#Override
public void onUpdate(float pSecondsElapsed) {
targets = targetLL.iterator();
while (targets.hasNext()) {
_target = targets.next();
if (_target.getY() >= cameraHeight) {
// removeSprite(_target, targets);
tPool.recyclePoolItem(_target);
targets.remove();
Log.d("ok", "---------Looop Inside-----");
// fail();
break;
}
// i don't know whether below code is valid for this postion
mMainScene.setOnSceneTouchListener(new IOnSceneTouchListener() {
#Override
public boolean onSceneTouchEvent(Scene arg0,
TouchEvent pSceneTouchEvent) {
try {
// i can't use this two
final float touchX = pSceneTouchEvent.getX();
final float touchY = pSceneTouchEvent.getY();
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
//call to remove sprite
removeSprite(_target, targets);
}
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
}
targetLL.addAll(TargetsToBeAdded);
TargetsToBeAdded.clear();
}
};
code for adding target:
/** adds a target at a random location and let it move along the y-axis */
public void addTarget() {
Random rand = new Random();
int minX = mTargetTextureRegion.getWidth();
int maxX = (int) (mCamera.getWidth() - mTargetTextureRegion.getWidth());
int rangeX = maxX - minX;
Log.d("----point----", "minX:" + minX + "maxX:" + maxX + "rangeX:"
+ rangeX);
int rX = rand.nextInt(rangeX) + minX;
int rY = (int) mCamera.getHeight() + mTargetTextureRegion.getHeight();
Log.d("---Random x----", "Random x" + rX + "Random y" + rY);
//HERE I USE POOL TO CREATE NEW SPRITE
//tPool is object of TargetsPool Class
target = tPool.obtainPoolItem();
target.setPosition(rX, rY);
target.animate(100);
mMainScene.attachChild(target, 1);
mMainScene.registerTouchArea(target);
int minDuration = 2;
int maxDuration = 32;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
// MoveXModifier mod = new MoveXModifier(actualDuration, target.getX(),
// -target.getWidth());
MoveYModifier mody = new MoveYModifier(actualDuration,
-target.getHeight(), cameraHeight + 10);
target.registerEntityModifier(mody.deepCopy());
TargetsToBeAdded.add(target);
}
code for remove sprite when touched:
// ==============the method to remove sprite=====================
public void removeSprite(final AnimatedSprite _sprite, Iterator it) {
runOnUpdateThread(new Runnable() {
#Override
public void run() {
_target = _sprite;
mMainScene.detachChild(_target);
}
});
it.remove();
}
I use GenericPool to create new sprite.
I am not sure where I have to write code for the specific touched sprite and remove it.
ohh.. I found the solution here.
I implemented an IOnAreaTouchListener in BaseGameActivity class. So, my class declaration looks like:
public class CrazyMonkeyActivity extends BaseGameActivity implements
IOnAreaTouchListener
and my override method looks like:
#Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
final ITouchArea pTouchArea, final float pTouchAreaLocalX,
final float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
this.removeSprite((AnimatedSprite) pTouchArea);
return true;
}
return false;
}
And remove Sprite methods should be like:
// ==============the method to remove spirit=====================
public void removeSprite(final AnimatedSprite target) {
runOnUpdateThread(new Runnable() {
#Override
public void run() {
mMainScene.detachChild(target);
mMainScene.unregisterTouchArea(target);
System.gc();
}
});
}
To create continuous Spawn Sprite I use a time handler inside this method. Below method should be called inside onLoadScene() method:
/** a Time Handler for spawning targets Sprites, triggers every 2 second */
private void createSpriteSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
float mEffectSpawnDelay = 2f;
spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
new ITimerCallback() {
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
//position for random sprite
final float xPos = MathUtils.random(30.0f,
(cameraWidth - 30.0f));
final float yPos = MathUtils.random(30.0f,
(cameraHeight - 30.0f));
//below method call for new sprite
addTarget(xPos, yPos);
}
});
getEngine().registerUpdateHandler(spriteTimerHandler);
}
And addTarget() looks like:
public void addTarget(float xPos, float yPos) {
Random rand = new Random();
Log.d("---Random x----", "Random x" + xPos + "Random y" + yPos);
target = new AnimatedSprite(xPos, yPos, mTargetTextureRegion);
target.animate(100);
mMainScene.attachChild(target);
mMainScene.registerTouchArea(target);
int minDuration = 2;
int maxDuration = 32;
int rangeDuration = maxDuration - minDuration;
int actualDuration = rand.nextInt(rangeDuration) + minDuration;
MoveYModifier mody = new MoveYModifier(actualDuration,
-target.getHeight(), cameraHeight + 10);
target.registerEntityModifier(mody.deepCopy());
}
Hope this might help others too!