AndEngine Box2D. Crash game after remove Joint with collides - android

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.

Related

harpoon as the pang game in libgdx

I am using Scene2D.
This is my Shoot Actor
public class ActorDisparo extends Actor {
private TextureRegion textureDisparo = new TextureRegion();
private World world;
public static Body body;
//private Fixture fixture;
private FixtureDef fdef;
private String userData;
private float anchoDisparo, altoDisparo;
private float positionX,positionY;
private static float porcentajeDeancho = 0,anchoMediano = 0, anchoPequeno = 0, anchoDiminuto = 0;
private TextureRegion arponRegion = new TextureRegion();
public ActorDisparo(World world, TextureRegion disparo, Vector2 position, float anchoDisparo, float altoDisparo, float fuerzaX, float fuerzaY, String userData){
this.textureDisparo = disparo;
this.world = world;
this.anchoDisparo = anchoDisparo;
this.altoDisparo = altoDisparo;
this.userData = userData;
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(position);
bodyDef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bodyDef);
PolygonShape shapeDisparo = new PolygonShape();
shapeDisparo.setAsBox((anchoDisparo/2)/2,altoDisparo/2);
fdef = new FixtureDef();
fdef.shape = shapeDisparo;
//fdef.restitution = 0.70f;
fdef.filter.categoryBits = BolasGame.DISPARO_BIT;
fdef.filter.maskBits = BolasGame.BOLAROJA_BIT |
BolasGame.TECHO_BIT;
body.createFixture(fdef).setUserData(userData);
shapeDisparo.dispose();
body.setGravityScale(0f);
body.applyLinearImpulse(fuerzaX,fuerzaY,position.x,position.y,true);
setSize( anchoDisparo *BolasGame.MetrosAPixels ,altoDisparo*BolasGame.MetrosAPixels);
//setBounds(0, 0, getWidth(), getHeight());
}
public float getPositionX() {
return getPositionX();
}
public float getPositionY() {
return getPositionY();
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
setPosition( (body.getPosition().x * BolasGame.MetrosAPixels) - getWidth()/2, (body.getPosition().y * BolasGame.MetrosAPixels) - getHeight()/2);
batch.draw(textureDisparo,getX(),getY(),getWidth(),getHeight());
}
public void detach(){
world.destroyBody(body);
remove();
}
}
and this is the call to shoot class
if(Gdx.input.justTouched() && hasdisparado == false){
hasdisparado =true;
touch = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
stage.getCamera().unproject(touch);
arponRegion = new TextureRegion(textureDisparo, 0, 0, 20, 40);
actorDisparo = new ActorDisparo(world,arponRegion,new Vector2(touch.x/BolasGame.MetrosAPixels,touch.y/BolasGame.MetrosAPixels ),20/BolasGame.MetrosAPixels,40/BolasGame.MetrosAPixels,0,2f,BolasGame.USERDATA_DISPARO);
stage.addActor(actorDisparo);
}
this creates a shot like a bullet but I need since I touched the screen until it is destroyed is continuous like the harpoon of game pang
the textureregion the charge of a texture whose dimensions are 446x20
textureDisparo = new Texture("gfx/disparo.png");
I have no idea how to do this because you have to repeat the image and body in box2d for collisions.
I totally lost
if someone can give me an idea would appreciate
Thank you
(Sorry for my English, I'm learning now)

Andegine error load map when output have :horizontal stripes

Andegine error load map when output have :horizontal stripes
i have load map, but have horizontal stripes in maps. i dont know. please help me.i am new developer,i use andegine. Can anyone help me with this problem? Any idea?
the image :
the code
public class TileActivity
extends SimpleBaseGameActivity {
private TMXTiledMap mTMXTiledMap;
private BoundCamera mBoundChaseCamera;
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
private Scene mScene;
private static final long[] ANIMATE_DURATION = new long[] { 200, 200, 200 };
private static final int PLAYER_VELOCITY = 2;
private BitmapTextureAtlas mTexturePlayer;
private Body mPlayerBody;
private TiledTextureRegion mPlayerTextureRegion;
private BitmapTextureAtlas mOnScreenControlTexture;
private TextureRegion mOnScreenControlBaseTextureRegion;
private TextureRegion mOnScreenControlKnobTextureRegion;
private DigitalOnScreenControl mDigitalOnScreenControl;
private PhysicsWorld mPhysicsWorld;
private TMXLayer layer;
#Override
protected void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
// Control texture
this.mOnScreenControlTexture = new BitmapTextureAtlas(getTextureManager(), 256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);
// Player sprite texture
this.mTexturePlayer = new BitmapTextureAtlas(getTextureManager(), 96, 128, TextureOptions.DEFAULT);
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mTexturePlayer, this, "hero.png", 0, 0, 3, 4);
// Load the textures
this.mTexturePlayer.load();
this.mOnScreenControlTexture.load();
}
#Override
protected Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
// Create physics world
this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0), false, 8, 1);
// Create the scene and register the physics world
mScene = new Scene();
mScene.registerUpdateHandler(this.mPhysicsWorld);
// Load the TMX map
try {
final TMXLoader tmxLoader = new TMXLoader(this.getAssets(),
this.mEngine.getTextureManager(),
TextureOptions.BILINEAR_PREMULTIPLYALPHA,
getVertexBufferObjectManager(),
new TMXLoader.ITMXTilePropertiesListener() {
#Override
public void onTMXTileWithPropertiesCreated(final TMXTiledMap pTMXTiledMap, final TMXLayer pTMXLayer, final TMXTile pTMXTile, final TMXProperties<TMXTileProperty> pTMXTileProperties) {}
});
this.mTMXTiledMap = tmxLoader.loadFromAsset("test.tmx");
} catch (final TMXLoadException tmxle) {
Debug.e(tmxle);
}
// Add the non-object layers to the scene
for (int i = 0; i < this.mTMXTiledMap.getTMXLayers().size(); i++) {
layer = this.mTMXTiledMap.getTMXLayers().get(i);
if (!layer.getTMXLayerProperties().containsTMXProperty("wall", "true")) {
mScene.attachChild(layer);
}
}
// Read in the unwalkable blocks from the object layer and create boxes for each
this.createUnwalkableObjects(mTMXTiledMap);
// Add outer walls
this.addBounds(layer.getWidth(), layer.getHeight());
this.mBoundChaseCamera.setBounds(0, layer.getWidth(), 0, layer.getHeight());
// Calculate the coordinates for the player, so it's centred on the camera.
final int centerX = (int) (CAMERA_WIDTH - this.mPlayerTextureRegion.getWidth()) / 2;
final int centerY = (int) (CAMERA_HEIGHT - this.mPlayerTextureRegion.getHeight()) / 2;
// Create the player sprite and add it to the scene.
final AnimatedSprite player = new AnimatedSprite(centerX, centerY, this.mPlayerTextureRegion, getVertexBufferObjectManager());
this.mBoundChaseCamera.setChaseEntity(player);
final FixtureDef playerFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 0.5f);
mPlayerBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, player, BodyDef.BodyType.DynamicBody, playerFixtureDef);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(player, mPlayerBody, true, false) {
#Override
public void onUpdate(float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
mBoundChaseCamera.updateChaseEntity();
}
});
mScene.attachChild(player);
// Add the control
this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mBoundChaseCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, getVertexBufferObjectManager(),
new BaseOnScreenControl.IOnScreenControlListener() {
#Override
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
// Set the correct walking animation
if (pValueY == 1) {
// Up
if (playerDirection != PlayerDirection.UP) {
player.animate(ANIMATE_DURATION, 0, 2, true);
playerDirection = PlayerDirection.UP;
}
} else if (pValueY == -1) {
// Down
if (playerDirection != PlayerDirection.DOWN) {
player.animate(ANIMATE_DURATION, 9, 11, true);
playerDirection = PlayerDirection.DOWN;
}
} else if (pValueX == -1) {
// Left
if (playerDirection != PlayerDirection.LEFT) {
player.animate(ANIMATE_DURATION, 3, 5, true);
playerDirection = PlayerDirection.LEFT;
}
} else if (pValueX == 1) {
// Right
if (playerDirection != PlayerDirection.RIGHT) {
player.animate(ANIMATE_DURATION, 6, 8, true);
playerDirection = PlayerDirection.RIGHT;
}
} else {
if (player.isAnimationRunning()) {
player.stopAnimation();
playerDirection = PlayerDirection.NONE;
}
}
// Set the player's velocity
mPlayerBody.setLinearVelocity(pValueX * PLAYER_VELOCITY, pValueY * PLAYER_VELOCITY);
}
});
this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f);
this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
this.mDigitalOnScreenControl.getControlBase().setScale(1.25f);
this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f);
this.mDigitalOnScreenControl.getControlKnob().setAlpha(0.5f);
this.mDigitalOnScreenControl.refreshControlKnobPosition();
mScene.setChildScene(this.mDigitalOnScreenControl);
return mScene;
}
#Override
public EngineOptions onCreateEngineOptions() {
this.mBoundChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), this.mBoundChaseCamera);
}
private enum PlayerDirection {
NONE,
UP,
DOWN,
LEFT,
RIGHT
}
private PlayerDirection playerDirection = PlayerDirection.NONE;
private void createUnwalkableObjects(TMXTiledMap map) {
// Loop through the object groups
for (final TMXObjectGroup group : this.mTMXTiledMap.getTMXObjectGroups()) {
if (group.getTMXObjectGroupProperties().containsTMXProperty("wall", "true")) {
// This is our "wall" layer. Create the boxes from it
for (final TMXObject object : group.getTMXObjects()) {
final Rectangle rect = new Rectangle(object.getX(), object.getY(), object.getWidth(), object.getHeight(), getVertexBufferObjectManager());
final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 1f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, rect, BodyDef.BodyType.StaticBody, boxFixtureDef);
rect.setVisible(false);
mScene.attachChild(rect);
}
}
}
}
private void addBounds(float width, float height) {
final Rectangle bottom = new Rectangle(0, height - 2, width, 2, getVertexBufferObjectManager());
bottom.setVisible(false);
final Rectangle top = new Rectangle(0, 0, width, 2, getVertexBufferObjectManager());
top.setVisible(false);
final Rectangle left = new Rectangle(0, 0, 2, height, getVertexBufferObjectManager());
left.setVisible(false);
final Rectangle right = new Rectangle(width - 2, 0, 2, height, getVertexBufferObjectManager());
right.setVisible(false);
final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0, 1f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, bottom, BodyDef.BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, top, BodyDef.BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyDef.BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyDef.BodyType.StaticBody, wallFixtureDef);
this.mScene.attachChild(bottom);
this.mScene.attachChild(top);
this.mScene.attachChild(left);
this.mScene.attachChild(right);
}
}
This is generally caused by pixel blending, which happens in the following situations:
If the texture is rendered smaller than native size, the pixels are averaged and values from neighboring pixels affect the edges of the tiles.
If the texture is rendered larger than native size, pixel values are interpolated, which also causes values from neighboring pixels to affect the edges of the tiles.
If the texture is not rendered exactly aligned to a pixel, interpolation also occurs.
So to avoid it, either make sure none of the above happens or disable texture filtering (putting it on nearest neighbor).
Nearest neighbor filtering of course doesn't look nice when the map gets scaled, so if you want to support this case you can alternatively make sure that each tile is surrounded by pixels that match the color of its edge pixels. This avoids colors from other tiles affecting its borders.

Newton's cradle on andengine, box2d

i'm trying to create something like Newton's cradle. But when one ball hits another, all balls move simultaneously in same direction. How can I decide this problem? Should i create another physical options of balls in createFixtureDef? Or I need to use some specific algorithm to transfer impuls between balls?
public class MainActivity extends SimpleBaseGameActivity implements IAccelerationListener,
IOnAreaTouchListener
{
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private BitmapTextureAtlas mBitmapTextureAtlas;
final String TAG = "States";
private Scene mScene;
protected ITiledTextureRegion mBoxFaceTextureRegion;
protected ITiledTextureRegion mCircleFaceTextureRegion;
protected PhysicsWorld mPhysicsWorld;
#Override
public EngineOptions onCreateEngineOptions() {
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
}
#Override
protected void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32
this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32
this.mBitmapTextureAtlas.load();
}
#Override
protected Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mScene = new Scene();
this.mScene.setBackground(new Background(0, 0, 0));
//this.mScene.setOnSceneTouchListener(this);
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
this.initJoints(mScene);
this.mScene.registerUpdateHandler(this.mPhysicsWorld);
this.mScene.setOnAreaTouchListener(this);
return this.mScene;
}
private void initJoints(final Scene pScene) {
final float centerY = CAMERA_HEIGHT / 2;
final float spriteWidth = this.mBoxFaceTextureRegion.getWidth();
final float spriteHeight = this.mBoxFaceTextureRegion.getHeight();
final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(30, 0.2f, 0.2f);
for(int i = 0; i < 10; i++) {
final float anchorFaceX = 100 + i * spriteWidth ;
final float anchorFaceY = centerY;
final AnimatedSprite anchorFace = new AnimatedSprite(anchorFaceX, anchorFaceY,
this.mBoxFaceTextureRegion, this.getVertexBufferObjectManager());
final Body anchorBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld,
anchorFace, BodyType.StaticBody,
objectFixtureDef);
final AnimatedSprite movingFace = new AnimatedSprite(anchorFaceX, anchorFaceY + 150,
this.mCircleFaceTextureRegion, this.getVertexBufferObjectManager()) ;
// movingFace.setScale(1.2f);
final Body movingBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld,
movingFace, BodyType.DynamicBody, objectFixtureDef);
movingFace.setUserData(movingBody);
// anchorFace.setScale(1.2f);
anchorFace.animate(200);
anchorFace.animate(200);
final Line connectionLine = new Line(anchorFaceX + spriteWidth / 2,
anchorFaceY + spriteHeight / 2,
anchorFaceX + spriteWidth / 2,
anchorFaceY + spriteHeight / 2,
this.getVertexBufferObjectManager());
pScene.registerTouchArea(movingFace);
pScene.attachChild(connectionLine);
pScene.attachChild(anchorFace);
pScene.attachChild(movingFace);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(anchorFace,
anchorBody, true, true){
#Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
final Vector2 movingBodyWorldCenter = movingBody.getWorldCenter();
connectionLine.setPosition(connectionLine.getX1(), connectionLine.getY1(),
movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT,
movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT);
}
});
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true));
final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter());
this.mPhysicsWorld.createJoint(revoluteJointDef);
}
}
#Override
public void onAccelerationAccuracyChanged(final AccelerationData pAccelerationData) {
}
#Override
public void onAccelerationChanged(final AccelerationData pAccelerationData) {
final Vector2 gravity = Vector2Pool.obtain(pAccelerationData.getX(), pAccelerationData.getY());
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
public boolean onAreaTouched( final TouchEvent pSceneTouchEvent,
final ITouchArea pTouchArea,final float pTouchAreaLocalX,
final float pTouchAreaLocalY) {
if(pSceneTouchEvent.isActionMove())
{
float touchX = pSceneTouchEvent.getX();
float touchY = pSceneTouchEvent.getY();
Log.d(TAG, "move to in X" +touchX + "n Y " +touchY);
final AnimatedSprite anchorFace = (AnimatedSprite) pTouchArea;
final Body tochedBody = (Body)anchorFace.getUserData();
//move sprite to xy
final float x = pSceneTouchEvent.getX();
final float y = pSceneTouchEvent.getY();
final float widthD2 = anchorFace.getWidth() / 2;
final float heightD2 = anchorFace.getHeight() / 2;
final float angle = tochedBody.getAngle(); // keeps the body angle
final Vector2 v2 = Vector2Pool.obtain((x + widthD2) / 32, (y + heightD2) / 32);
tochedBody.setTransform(v2, angle);
Vector2Pool.recycle(v2);
return true;
}
return false;
}
}
Unfortunately Box2D is not really suitable for this.
In my experience, you can get one or two swing-thrus to work as long as the balls are not touching each other to start with. That is, each ball starts with a very small gap between it and the neighbor on each side. This means that when they collide each collision is solved using just two balls at a time, for a total of 4 separate collisions for the impact to travel to the other side (for 5 balls), instead of solving all 5 balls as a single 'island'.
Trouble is, the positioning needs to be very precise, and after a few swings the balls stray from that, so that you end up with collisions involving more than two balls at a time. I only ever saw at most 2-3 swings work as desired...

How do I apply physics on moving Ball which Collide with non moving ball - AndEngine

I'm creating Demo application in which 2 Ball one is moving and one is static (Not moving) . I just want to collide both of them at run time. but my moving object not moving when i apply update position true in this line of code:
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ball, body, false, true));
here is my code
public class DizyBall extends SimpleBaseGameActivity implements IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 740;
private static final int CAMERA_HEIGHT = 480;
private static final float DEMO_VELOCITY = 150.0f;
// ===========================================================
// Fields
// ===========================================================
private Scene mScene;
private PhysicsWorld mPhysicsWorld;
private Body body;
private FixtureDef objectFixtureDef ;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mFaceTextureRegion;
private TextureRegion mColiTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
#Override
public EngineOptions onCreateEngineOptions() {
final Camera camera = new Camera(0, 0, DizyBall.CAMERA_WIDTH, DizyBall.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(DizyBall.CAMERA_WIDTH, DizyBall.CAMERA_HEIGHT), camera);
}
#Override
public void onCreateResources() {
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 48, 48, TextureOptions.BILINEAR);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "ball.png", 0, 0, 1, 1);
this.mColiTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "ball.png",0,0);
this.mBitmapTextureAtlas.load();
}
#Override
public Scene onCreateScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
mScene = new Scene();
mScene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f));
mScene.setOnSceneTouchListener(this);
objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0), false, 3, 2);
final float centerX = (DizyBall.CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final float centerY = (DizyBall.CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final Sprite Coli = new Sprite(centerX, centerY, this.mColiTextureRegion, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, Coli, BodyType.DynamicBody, objectFixtureDef);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(Coli, body, true, true));
mScene.attachChild(Coli);
this.mScene.registerUpdateHandler(this.mPhysicsWorld);
return mScene;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
// pSceneTouchEvent
if(this.mPhysicsWorld != null) {
if(pSceneTouchEvent.isActionUp()){
final Ball ball = new Ball(pSceneTouchEvent.getX(), pSceneTouchEvent.getY(), this.mFaceTextureRegion, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, ball, BodyType.DynamicBody, objectFixtureDef);
this.mScene.attachChild(ball);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ball, body, false, true));
return false;
}
}else{
Log.v("PhysicsWorld","NULL");
}
return false;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static class Ball extends AnimatedSprite {
private final PhysicsHandler mPhysicsHandler;
public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.mPhysicsHandler = new PhysicsHandler(this);
this.registerUpdateHandler(this.mPhysicsHandler);
this.mPhysicsHandler.setVelocity(DizyBall.DEMO_VELOCITY, DizyBall.DEMO_VELOCITY);
}
#Override
protected void onManagedUpdate(final float pSecondsElapsed) {
if(this.mX < 0) {
this.mPhysicsHandler.setVelocityX(DizyBall.DEMO_VELOCITY);
} else if(this.mX + this.getWidth() > DizyBall.CAMERA_WIDTH) {
this.mPhysicsHandler.setVelocityX(-DizyBall.DEMO_VELOCITY);
}
if(this.mY < 0) {
this.mPhysicsHandler.setVelocityY(DizyBall.DEMO_VELOCITY);
} else if(this.mY + this.getHeight() > DizyBall.CAMERA_HEIGHT) {
this.mPhysicsHandler.setVelocityY(-DizyBall.DEMO_VELOCITY);
}
super.onManagedUpdate(pSecondsElapsed);
}
}
}
Bellow is the Image at run time but both are not Collide.
Just add this line after mScene.registerUpdateHandler(this.mPhysicsHandler);
mScene.registerUpdateHandler(this);
Then implement the updatehandler and add the unimplemented methods, now you can do anything in the onUpdate method, like
body.setLinearVelocity(10,10);
to make it collide with the other object.

how to move body of sprite using andEngine?

I want to move body of the sprite along with line in some portion of line, just i able to move sprite only but body is not moving.
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene(2);
scene.setBackground(new ColorBackground(0.09804f, 0.00274f, 0.0784f));
this .enableAccelerometerSensor(this );
this.sPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH,2);
final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
final Shape right = new Rectangle(CAMERA_WIDTH-2, 0,2, CAMERA_HEIGHT);
PhysicsFactory.createBoxBody(this.sPhysicsWorld, ground,
BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.sPhysicsWorld, roof,
BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.sPhysicsWorld, left,
BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.sPhysicsWorld, right,
BodyType.StaticBody, wallFixtureDef);
scene.getFirstChild().attachChild(ground);
scene.getFirstChild().attachChild(roof);
scene.getFirstChild().attachChild(left);
scene.getFirstChild().attachChild(right);
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion);
final Body bodyRedBall = PhysicsFactory.createCircleBody(this.sPhysicsWorld, face,
BodyType.DynamicBody, wallFixtureDef);
this.sPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, bodyRedBall, true, true));
scene.attachChild(face);
final AnimatedSprite face2 = new AnimatedSprite(100, 100, this.mFaceTextureRegion);
final Body bodyRedBall2 = PhysicsFactory.createCircleBody(this.sPhysicsWorld, face2,
BodyType.KinematicBody, wallFixtureDef);
final Path path4 = new Path(3).to(682, 223).to(482, 223).to(682, 223);
face2.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path4, null, new IPathModifierListener() {
#Override
public void onWaypointPassed(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
}
})));
this.sPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face2, bodyRedBall2, true, true){
#Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
face2.setPosition(face2.getX(), face2.getY());
}
});
scene.attachChild(face2);
scene.registerUpdateHandler(this.sPhysicsWorld);
return scene;
}
#Override
public void onLoadComplete() {
}
#Override
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
// TODO Auto-generated method stub
final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getY(), pAccelerometerData.getX());
this.sPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
You can use body.setLinearVelocity(); to move the body, the sprite will automatically follow the body because you have specified a physics connector.
public class MoveBodyModifier extends MoveModifier {
private Body mBody;
public MoveBodyModifier(float pDuration, float pFromX, float pToX, float pFromY, float pToY, Body body) {
super(pDuration, pFromX, pToX, pFromY, pToY);
mBody = body;
}
#Override
protected void onSetInitialValues(IEntity pEntity, float pX, float pY) {
mBody.setTransform(pX/ PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT,
pY/ PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT, mBody.getAngle());
}
#Override
protected void onSetValues(IEntity pEntity, float pPercentageDone, float pX, float pY) {
mBody.setTransform(pX/ PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT,
pY/ PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT, mBody.getAngle());
}
}
to move the body must use the setTransform
yourBody.setTransform(new Vector2(x/32,y/32), 0);
and remember that you have to divide x and y default by 32
you can also go
yourBody.setTransform(x/32,y/32), 0);
and you need to divide by 32 because box2d does not operates in pixels so to get it to pixels you need to divide by 32

Categories

Resources