I am new in AndEngine. I use animatedSprite and Sprite Object. I want to move Sprite on the basis of accelerometer but i dont want to move animatedSprite also. I want physicsworld implementation
private void addBottomFace(final float pX, final float pY) {
myBottomSticFace = new Sprite(pX, pY, myBottomStickTextureRegion);
myBottomStickBody = PhysicsFactory.createBoxBody(this.myPhysicsWorld, myBottomSticFace, BodyType.DynamicBody, myFixtureDef);
this.myScene.attachChild(myBottomSticFace);
this.myPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(myBottomSticFace, myBottomStickBody, true, true));
}
#Override
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY());
myBottomSticFace.setPosition(myBottomSticFace,getX() + pAccelerometerData.getX(), myBottomSticFace,getY());
Vector2Pool.recycle(gravity);
}
With this code mBottomSticFace will move according to accelerometer but body does not moves.
You should create two different bodies and attach it to your sprites.
The Body you want to be moved should be set as BodyType.DynamicBody, and the other one should be BodyType.StaticBody.
To see accelerometer and body examples, check this:
http://code.google.com/p/andengineexamples/source/browse/src/org/anddev/andengine/examples/PhysicsExample.java
Related
I'm currently using AndEngine, to do a little box game with faces in it, so that the player spawns faces when touching the screen. So here I already declared the variable "onch" as a double and I made it a random number between 1 and 4 so that each time addFace is called, it generates a new number and so a new face. However I'm getting always the last face. I'm getting only this :
face = new AnimatedSprite(pX, pY, this.mort, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
Here is the full code :
private void addFace(final float pX, final float pY) {
onch = Math.floor((Math.random()*4)+1);
final AnimatedSprite face;
final Body body;
if(onch == 4) {
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else if (onch == 3) {
face = new AnimatedSprite(pX, pY, this.noel, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else if (onch == 2) {
face = new AnimatedSprite(pX, pY, this.sournois, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else {
face = new AnimatedSprite(pX, pY, this.mort, this.getVertexBufferObjectManager());
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
}
face.animate(200);
this.mScene.attachChild(face);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true));
}
Why do I only receive the one value?
i think it is because you set your variables with the
final
modifier, once you set an instance of a final variable it cannot be changed, so your random code works fine but since the variables have the final modifier, once they are set the first time they are stuck like that, you cannot change them
There are some problems with the code.
This line body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); appears in the code four times. You could take it out of your if statements because it's the same in all four.
As JRowan said, final should not be use in this case.
Now, if you are sure that the face is exactly identical at the end of this method, the problem is in one of these calls: AnimatedSprite()constructor might give you the same face no matter what arguments you put in, or animate() method of AnimatedSprite class changes the face and makes it look the same in the end.
This appears incorrect:
onch = Math.floor((Math.random()*4)+1);
Try:
onch = Math.floor((Math.random()%4)+1);
I am trying to create simple tennis game. Each side has a wall. There are also a box and a ball. My environment doesn't have gravity. The box and the ball don't have any velocity. When the box contacts the ball(I move this by mouse with different speed), it(the ball) just changes its position and doesn't continue moving and sometimes these objects don't collide with each other:
I want the box can strike the ball using different angle and strength.
How can I do this? What should I change in the properties of the ball and the box?
The code snippet is below:
public void createBall(Vector2 position, Vector2 velocity, float angle, Object userData){
// First we create a body definition
BodyDef bodyDef = new BodyDef();
// We set our body to dynamic, for something like ground which doesnt move we would set it to StaticBody
bodyDef.type = BodyType.DynamicBody;
// Set our body's starting position in the world
bodyDef.position.set(position);
// Create our body in the world using our body definition
Body body = world.createBody(bodyDef);
body.setUserData(userData);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(10f);
PolygonShape poly = new PolygonShape();
poly.setAsBox(12, 12);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.0f;
fixtureDef.friction = 0.2f;
fixtureDef.restitution = 1f; // Make it bounce a little bit
fixtureDef.isSensor=false;
// Create our fixture and attach it to the body
Fixture f = body.createFixture(fixtureDef);
f.setUserData("ball");
circle.dispose();
}
private Body createBox(World world, float width, float height, float density) {
BodyDef def = new BodyDef();
def.type = BodyType.KinematicBody;
Body box = world.createBody(def);
PolygonShape poly = new PolygonShape();
poly.setAsBox(width/2, height/2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = poly;
fixtureDef.density = 0.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.1f; // Make it bounce a little bit
fixtureDef.isSensor=false;
// Create our fixture and attach it to the body
Fixture f = box.createFixture(fixtureDef);
f.setUserData("platform");
poly.dispose();
return box;
}
public void createWall(World world, Vector2 position, float hx, float hy){
// Create our body definition
BodyDef groundBodyDef =new BodyDef();
// Set its world position
groundBodyDef.position.set(position);
groundBodyDef.type=BodyType.StaticBody;
// Create a body from the defintion and add it to the world
Body groundBody = world.createBody(groundBodyDef);
// Create a polygon shape
PolygonShape groundBox = new PolygonShape();
// Set the polygon shape as a box which is twice the size of our view port and 20 high
// (setAsBox takes half-width and half-height as arguments)
groundBox.setAsBox(hx, hy);
// Create a fixture from our polygon shape and add it to our ground body
groundBody.createFixture(groundBox, 0.0f);
// Clean up after ourselves
groundBox.dispose();
}
You are moving your box by changing its position. But an important part of collision resolution is velocity. And your box's velocity is always zero (from box2d look point). Thus you experience strange collision resolution
I think your screen width and height are too large... if that's the case try using world width and height ... 20x12 units.. not 800x480 something .
Box2D doesn't like bodies, which fixtures has density 0. Usual, simulation performs somehow, but behaviour is not correct. Try value 0.3 for example.
Overlap problem may be solved by setting flag b2BodyDef::bullet. There description from Box2D reference:
bool b2BodyDef::bullet
Is this a fast moving body that should be prevented from tunneling through other moving bodies? Note that all bodies are prevented from tunneling through kinematic and static bodies. This setting is only considered on dynamic bodies.
Warning:
You should use this flag sparingly since it increases processing time.
I am trying to develop a live wallpaper using andengine gles2 anchor center , with some physics.But when i add a physics object it was moving upwards.instead of moving downward due to gravity
what are the mistakes i am making
please help me to sort out the issue
Here is my code
FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f,
0.5f);
mPhysicsWorld = new PhysicsWorld(new Vector2(0,
SensorManager.GRAVITY_EARTH), false);
final AnimatedSprite animatedSprite;
animatedSprite = new AnimatedSprite(500, 250,
this.mBoxFaceTextureRegion, this.getVertexBufferObjectManager());
body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, animatedSprite,
BodyType.DynamicBody, FIXTURE_DEF);
scene.attachChild(animatedSprite);
animatedSprite.animate(200);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
animatedSprite, body, true, true));
Just multiply SensorManager.GRAVITY_EARTH by -1.
Setting negative gravity did not respond properly to sensor data. By adding acceleration to the sensor data in the overridden method **onAccelerationChanged()**, could make the bject falling down with sensor flat.
public void onAccelerationChanged(final AccelerationData pAccelerationData) {
/* Add constant value for vertical gravity*/
final Vector2 gravity = Vector2Pool.obtain(pAccelerationData.getX(), pAccelerationData.getY() + 4.0);
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
This will make your phy world in real gravity experience and you will get objects influenced by sensor data properly
I'm developing a simple game by andengine.
I have 10 balls which are moving randomly on screen.i'm importing the balls as picture in sprites.if they move at the same coordinate , they pass though their own insides.but i want: if they move at the same coodirnates ,they should change their directions.so they cannot pass through their insides.how can i do that?
private Runnable mStartCircle = new Runnable() {
public void run() {
int i = circleNumber++;
Scene scene = Level1Activity.this.mEngine.getScene();
float startY = -64.0f;
float startX = randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
float a= randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
circles[i] = new Sprite(startX, startY, textRegCircle[i]);
circles[i].registerEntityModifier(
(IEntityModifier) new SequenceEntityModifier (
new MoveModifier(10.0f, circles[i].getX(), a,
circles[i].getY(),CAMERA_HEIGHT+64.0f)));
}
scene.getLastChild().attachChild(circles[i]);
if (circleNumber < 10){
mHandler.postDelayed(mStartCircle,1000);
}
}
};
Each object(ball) requires a bounding box, or in your case a bounding circle, which is equal to the size of your sprite.
When the game updates and any balls position changes, you have to test for collisions.
Circle to circle collision testing is the simplest type to do.
if distance between (ball1.pos + ball2.pos) is less than (ball1.radius + ball2.radius) = collision.
You then handle the collision by reversing the velocities or calculating new momentums or something. (You also need to move the objects apart so they are no longer colliding)
Just apply a physical connector between balls:
so it will collide and bounce back.
final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f, 0.5f, 0.5f);
final Body ballBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, circles[i],BodyType.DynamicBody, boxFixtureDef);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(circles[i], ballBody, true, true));
this.mScene.attachChild(circles[i]);
I'm creating an android app using Andengine. One part of the app requires users to select a few sprites from a group of sprites on the screen, which causes the selected sprites to turn a different color (ie, moving to the next tile). I declared them all as animated sprites and I'm using the same texture for each one. The problem is that once I select a sprite, every sprite moves to the next tile, not just the one I selected. How do I make just the one sprite change?
Here's where I setup the textures and whatnot:
private Texture mGreenTextureAtlas;
private TiledTextureRegion mGreenBallFaceTextureRegion;
#Override
public void onLoadResources() {
/* Textures. */
...
this.mGreenTextureAtlas = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
...
TextureRegionFactory.setAssetBasePath("gfx/");
/* TextureRegions. */
...
this.mGreenBallFaceTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mGreenTextureAtlas, this, "green_ball.png", 0, 16, 2, 1); // 64x32
this.mEngine.getTextureManager().loadTextures(this.mCueTextureAtlas, this.mGreenTextureAtlas , this.mBackgroundTexture, this.mPocketTexture);
}
Here's where I actually create the sprites and apply the textures:
face = new AnimatedSprite(pX, pY, this.mGreenBallFaceTextureRegion);
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
encapsed = new Encapsulator(body, face, Encapsulator.AVOID_BALL, mFaceCount);
ballsList.add(encapsed);
I encapsulate each sprite, it's body, and some other data into an object that I made, and then add that object into an ArrayList.
Here is the onTouch event handler.
#Override
public boolean onAreaTouched( final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea,final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
if(pSceneTouchEvent.isActionDown()) {
final AnimatedSprite face = (AnimatedSprite) pTouchArea;
for(int i=0; i<ballsList.size(); i++)
{
if(face.equals(ballsList.get(i).animatedFace))
{
ballsList.get(i).toggleType(face);
System.out.println("Ball " + ballsList.get(i).id + " is now " + ballsList.get(i).type);
}
}
return true;
}
return false;
}
Finally, here is the toggleType method in the Encapsulator class that's responsible for moving to the next tile:
public void toggleType(AnimatedSprite face)
{
if(this.type == AVOID_BALL)
{
this.type = HIT_BALL;
face.nextTile();
}
else if(this.type == HIT_BALL)
{
this.type = AVOID_BALL;
face.setCurrentTileIndex(0);
}
}
Sorry if this is a bit long-winded. Any help is appreciated.
I did some more googling and came across a solution. I had to use the textureregion.clone() method when creating the sprites. I found the solution at this link:
http://www.andengine.org/forums/development/two-sprites-sharing-the-same-tiledtextureregion-t4339.html