Search Results

Search found 248 results on 10 pages for 'box2d'.

Page 3/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • What causes Box2D revolute joints to separate?

    - by nbolton
    I have created a rag doll using dynamic bodies (rectangles) and simple revolute joints (with lower and upper angles). When my rag doll hits the ground (which is a static body) the bodies seem to fidget and the joints separate. It looks like the bodies are sticking to the ground, and the momentum of the rag doll pulls the joint apart (see screenshot below). I'm not sure if it's related, but I'm using the Badlogic GDX Java wrapper for Box2D. Here's some snippets of what I think is the most relevant code: private RevoluteJoint joinBodyParts( Body a, Body b, Vector2 anchor, float lowerAngle, float upperAngle) { RevoluteJointDef jointDef = new RevoluteJointDef(); jointDef.initialize(a, b, a.getWorldPoint(anchor)); jointDef.enableLimit = true; jointDef.lowerAngle = lowerAngle; jointDef.upperAngle = upperAngle; return (RevoluteJoint)world.createJoint(jointDef); } private Body createRectangleBodyPart( float x, float y, float width, float height) { PolygonShape shape = new PolygonShape(); shape.setAsBox(width, height); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; bodyDef.position.y = y; bodyDef.position.x = x; Body body = world.createBody(bodyDef); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = shape; fixtureDef.density = 10; fixtureDef.filter.groupIndex = -1; fixtureDef.filter.categoryBits = FILTER_BOY; fixtureDef.filter.maskBits = FILTER_STUFF | FILTER_WALL; body.createFixture(fixtureDef); shape.dispose(); return body; } I've skipped the method for creating the head, as it's pretty much the same as the rectangle method (just using a cricle shape). Those methods are used like so: torso = createRectangleBodyPart(x, y + 5, 0.25f, 1.5f); Body head = createRoundBodyPart(x, y + 7.4f, 1); Body leftLegTop = createRectangleBodyPart(x, y + 2.7f, 0.25f, 1); Body rightLegTop = createRectangleBodyPart(x, y + 2.7f, 0.25f, 1); Body leftLegBottom = createRectangleBodyPart(x, y + 1, 0.25f, 1); Body rightLegBottom = createRectangleBodyPart(x, y + 1, 0.25f, 1); Body leftArm = createRectangleBodyPart(x, y + 5, 0.25f, 1.2f); Body rightArm = createRectangleBodyPart(x, y + 5, 0.25f, 1.2f); joinBodyParts(torso, head, new Vector2(0, 1.6f), headAngle); leftLegTopJoint = joinBodyParts(torso, leftLegTop, new Vector2(0, -1.2f), 0.1f, legAngle); rightLegTopJoint = joinBodyParts(torso, rightLegTop, new Vector2(0, -1.2f), 0.1f, legAngle); leftLegBottomJoint = joinBodyParts(leftLegTop, leftLegBottom, new Vector2(0, -1), -legAngle * 1.5f, 0); rightLegBottomJoint = joinBodyParts(rightLegTop, rightLegBottom, new Vector2(0, -1), -legAngle * 1.5f, 0); leftArmJoint = joinBodyParts(torso, leftArm, new Vector2(0, 1), -armAngle * 0.7f, armAngle); rightArmJoint = joinBodyParts(torso, rightArm, new Vector2(0, 1), -armAngle * 0.7f, armAngle);

    Read the article

  • Box2D Difference Between WorldCenter and Position

    - by Free Lancer
    So this problem has been brothering for a couple of days now. First off, what is the difference between say Body.getWorldCenter() and Body.getPosition(). I heard that WorldCenter might have to do with the center of gravity or something. Second, When I create a Box2D Body for a sprite the Body is always at the lower left corner. I check it by printing a Rectangle of 1 pixel around the box.getWorldCenter(). From what I understand the Body should be in the center of the Sprite and its bounding box should wrap around the Sprite, correct? Here's an image of what I mean (The Sprite is Red, Body Blue): Here's some code: Body Creator: public static Body createBoxBody( final World pPhysicsWorld, final BodyType pBodyType, final FixtureDef pFixtureDef, Sprite pSprite ) { float pRotation = 0; float pCenterX = pSprite.getX() + pSprite.getWidth() / 2; float pCenterY = pSprite.getY() + pSprite.getHeight() / 2; float pWidth = pSprite.getWidth(); float pHeight = pSprite.getHeight(); final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; //boxBodyDef.position.x = pCenterX / Constants.PIXEL_METER_RATIO; //boxBodyDef.position.y = pCenterY / Constants.PIXEL_METER_RATIO; boxBodyDef.position.x = pSprite.getX() / Constants.PIXEL_METER_RATIO; boxBodyDef.position.y = pSprite.getY() / Constants.PIXEL_METER_RATIO; Vector2 v = new Vector2( boxBodyDef.position.x * Constants.PIXEL_METER_RATIO, boxBodyDef.position.y * Constants.PIXEL_METER_RATIO ); Gdx.app.log("@Physics", "createBoxBody():: Box Position: " + v); // Temporary Box shape of the Body final PolygonShape boxPoly = new PolygonShape(); final float halfWidth = pWidth * 0.5f / Constants.PIXEL_METER_RATIO; final float halfHeight = pHeight * 0.5f / Constants.PIXEL_METER_RATIO; boxPoly.setAsBox( halfWidth, halfHeight ); // set the anchor point to be the center of the sprite pFixtureDef.shape = boxPoly; final Body boxBody = pPhysicsWorld.createBody(boxBodyDef); Gdx.app.log("@Physics", "createBoxBody():: Box Center: " + boxBody.getPosition().mul(Constants.PIXEL_METER_RATIO)); boxBody.createFixture(pFixtureDef); boxBody.setTransform( boxBody.getWorldCenter(), MathUtils.degreesToRadians * pRotation ); boxPoly.dispose(); return boxBody; } Making the Sprite: public Car( Texture texture, float pX, float pY, World world ) { super( "Car" ); mSprite = new Sprite( texture ); mSprite.setSize( mSprite.getWidth() / 6, mSprite.getHeight() / 6 ); mSprite.setPosition( pX, pY ); mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2); FixtureDef carFixtureDef = new FixtureDef(); // Set the Fixture's properties, like friction, using the car's shape carFixtureDef.restitution = 1f; carFixtureDef.friction = 1f; carFixtureDef.density = 1f; // needed to rotate body using applyTorque mBody = Physics.createBoxBody( world, BodyDef.BodyType.DynamicBody, carFixtureDef, mSprite ); }

    Read the article

  • Box2D body rotation with setTransform

    - by thobens
    I' having a problem rotating a body with setTransform(), The body has multiple sensors that should rotate with the player. The rotation works but it rotates around the bodys local 0,0 position instead of the center. Note that the game is in a top-down perspective and the player can go in four different directions, thus I need to rotate him immediately (in one tick) in 90 degrees steps. Up: Down: I can't find a way to set the rotation center. Here's the code I use to rotate it: float angle = direction * 90 * MathUtils.degRad; // direction is an int value from 0 to 3 body.setTransform(body.getPosition(), angle); I also tried body.getLocalCenter().set() and bc.body.getMassData().center.set() but it didn't seem to have any effect. How can I rotate the body around its center?

    Read the article

  • BOX2D and AS3: Mouse Event not working

    - by Gabriel Meono
    Background: Trying to make a simple "drop the ball" game. The code is located inside the first frame of the timeline. Nothing more is on the stage. Issue: Using QuickBox2D I made a simple If statement that drops and object acording the Mouse-x position: if (MouseEvent.CLICK) { sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); I imported the MouseEvent library: import flash.events.MouseEvent; Nothing happens if I click, no output errors either. See it in action: http://gabrielmeono.com/download/Lucky_Hit_Alpha.swf http://gabrielmeono.com/download/Lucky_Hit_Alpha.fla Full Code: [SWF(width = 350, height = 600, frameRate = 60)] import com.actionsnippet.qbox.*; import flash.events.MouseEvent; var sim:QuickBox2D = new QuickBox2D(this); sim.createStageWalls(); //var ball:sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); // // make a heavy circle sim.addCircle({x:3, y:1, radius:0.25, density:5}); sim.addCircle({x:2, y:1, radius:0.25, density:5}); sim.addCircle({x:4, y:1, radius:0.25, density:5}); sim.addCircle({x:5, y:1, radius:0.25, density:5}); sim.addCircle({x:6, y:1, radius:0.25, density:5}); // create a few platforms sim.addBox({x:3, y:2, width:4, height:0.2, density:0, angle:0.1}); // make 26 dominoes for (var i:int = 0; i<7; i++){ //End sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0}); sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0}); //Mid end sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0}); sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0}); //Middle Start sim.addCircle({x:0 + i * 1.5, y:09, radius:0.1, density:0}); sim.addCircle({x:1 + i * 1.5, y:08, radius:0.1, density:0}); sim.addCircle({x:0 + i * 1.5, y:07, radius:0.1, density:0}); sim.addCircle({x:1 + i * 1.5, y:06, radius:0.1, density:0}); } if (MouseEvent.CLICK) { sim.addCircle({x:mouseX, y:1, radius:0.25, density:5}); sim.start(); /*sim.mouseDrag();*/ }

    Read the article

  • Box2D Static-Dynamic body joint eliminates collisions

    - by andrewz
    I have a static body A, and a dynamic body B, and a dynamic body C. A is filtered to not collide with anything, B and C collide with each other. I wish to create a joint between B and A. When I create a joint (ex. revolute), B no longer collides with C - C passes through it as if it does not exist. What am I doing wrong? How can adding a joint prevent a body from colliding with another body it used to? EDIT: I want to join B with A, and have B collide with C, but not A collide with C. In realistic terms, I'm trying to create a revolute joint between a wheel (B) and a wall (A), and have a box (C) hit the wheel and the wheel would then rotate. EDIT: I create a the simplest revolute joint I can with these parameters (C++): b2RevoluteJointDef def; def.Initialize(A, B, B -> GetWorldCenter()); world -> CreateJoint(&def);

    Read the article

  • PhysicsMouseJoint problem in andengine + Box2d

    - by Nikhil Lamba
    What we can remove from this code i.e from PhysicsMouseJointExample to remove the functionality of drag and drog of sprite but i need all functionality except this only user move the sprite with some force and velocity of fling but user can't move the ball as like drag and drop like moving a finger on screen and sprite move with finger plz plz help me I am Using Below method for Mouse Joint CODE : public MouseJoint createMouseJoint(final IShape pFace, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final Body body = (Body) pFace.getUserData(); final MouseJointDef mouseJointDef = new MouseJointDef(); final Vector2 localPoint = Vector2Pool.obtain((pTouchAreaLocalX - pFace.getWidth() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, (pTouchAreaLocalY - pFace.getHeight() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.groundBody.setTransform(localPoint, 0); mouseJointDef.bodyA = this.groundBody; mouseJointDef.bodyB = body; mouseJointDef.dampingRatio = 0.95f; mouseJointDef.frequencyHz = 30; mouseJointDef.maxForce = (200.0f * body.getMass()); mouseJointDef.collideConnected = true; mouseJointDef.target.set(body.getWorldPoint(localPoint)); Vector2Pool.recycle(localPoint); return (MouseJoint)mPhysicsWorld.createJoint(mouseJointDef); }

    Read the article

  • Box2d - Attaching a fired arrow to a moving enemy

    - by Satchmo Brown
    I am firing an arrow from the player to moving enemies. When the arrow hits the enemy, I want it to attach exactly where it hit and cause the enemy (a square) to tumble to the ground. Excluding the logistics of the movement and the spin (it already works), I am stuck on the attaching of the two bodies. I tried to weld them together initially but when they fell, they rotated in opposite directions. I have figured that a revolute joint is probably what I am after. The problem is that I can't figure out a way to attach them right where they collide. Using code from iforce2d: b2RevoluteJointDef revoluteJointDef; revoluteJointDef.bodyA = m_body; revoluteJointDef.bodyB = m_e->m_body; revoluteJointDef.collideConnected = true; revoluteJointDef.localAnchorA.Set(0,0);//the top right corner of the box revoluteJointDef.localAnchorB.Set(0,0);//center of the circle b2RevoluteJoint m_joint = *(b2RevoluteJoint*)m_game->m_world->CreateJoint( &revoluteJointDef ); m_body->SetLinearVelocity(m_e->m_body->GetLinearVelocity()); This attaches them but in the center of both of their points. Does anyone know how I would go about getting the exact point of collision so I can link these? Is this even the right method of doing this? Update: I have the exact point of collision. But I still am not sure this is even the method I want to go about this. Really, I just want to attach body A to B and have body B unaffected in any way.

    Read the article

  • AndEngine; Box2D - high speed body overlapping, prismatic joints

    - by Visher
    I'm trying to make good suspension for my car game, but I'm getting nervous of some problems with it. At the beginning, I've tried to make it out of one prismatic joint/revolute joint per one wheel only, but surprisingly prismatic joint that should only move in Y asix moves also in X axis, if car travels very fast, or even on low speeds if there's setContinuousPhysics = true. This causes wheels to "shift back", moving them away from axle. Now I've tried to add some bodies that will keep it in place: Suspension helper collides with spring only, wheel doesn't collide with spring&helper&vehicle body This is how I create those elements: rect = new Rectangle(1100, 1350, 200, 50, getVertexBufferObjectManager()); rect.setColor(Color.RED); scene.attachChild(rect); //rect.setRotation(90); Rectangle miniRect1 = new Rectangle(1102, 1355, 30, 50, getVertexBufferObjectManager()); miniRect1.setColor(0, 0, 1, 0.5f); miniRect1.setVisible(true); scene.attachChild(miniRect1); Rectangle miniRect2 = new Rectangle(1268, 1355, 30, 50, getVertexBufferObjectManager()); miniRect2.setColor(0, 0, 1, 0.5f); miniRect1.setVisible(true); scene.attachChild(miniRect2); rectBody = PhysicsFactory.createBoxBody( physicsWorld, rect, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f)); rectBody.setUserData("car"); Body miniRect1Body = PhysicsFactory.createBoxBody( physicsWorld, miniRect1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f)); miniRect1Body.setUserData("suspension"); Body miniRect2Body = PhysicsFactory.createBoxBody( physicsWorld, miniRect2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 10.0f)); miniRect2Body.setUserData("suspension"); physicsWorld.registerPhysicsConnector(new PhysicsConnector(rect, rectBody, true, true)); physicsWorld.registerPhysicsConnector(new PhysicsConnector(miniRect1, miniRect1Body, true, true)); physicsWorld.registerPhysicsConnector(new PhysicsConnector(miniRect2, miniRect2Body, true, true)); PrismaticJointDef miniRect1JointDef = new PrismaticJointDef(); miniRect1JointDef.initialize(rectBody, miniRect1Body, miniRect1Body.getWorldCenter(), new Vector2(0.0f, 0.3f)); miniRect1JointDef.collideConnected = false; miniRect1JointDef.enableMotor= true; miniRect1JointDef.maxMotorForce = 15; miniRect1JointDef.motorSpeed = 5; miniRect1JointDef.enableLimit = true; physicsWorld.createJoint(miniRect1JointDef); PrismaticJointDef miniRect2JointDef = new PrismaticJointDef(); miniRect2JointDef.initialize(rectBody, miniRect2Body, miniRect2Body.getWorldCenter(), new Vector2(0.0f, 0.3f)); miniRect2JointDef.collideConnected = false; miniRect2JointDef.enableMotor= true; miniRect2JointDef.maxMotorForce = 15; miniRect2JointDef.motorSpeed = 5; miniRect2JointDef.enableLimit = true; physicsWorld.createJoint(miniRect2JointDef); scene.attachChild(karoseriaSprite); Rectangle r1 = new Rectangle(1050, 1300, 52, 150, getVertexBufferObjectManager()); r1.setColor(0, 1, 0, 0.5f); r1.setVisible(true); scene.attachChild(r1); Body r1body = PhysicsFactory.createBoxBody(physicsWorld, r1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.001f, 0.01f)); r1body.setUserData("suspensionHelper"); physicsWorld.registerPhysicsConnector(new PhysicsConnector(r1, r1body, true, true)); WeldJointDef r1jointDef = new WeldJointDef(); r1jointDef.initialize(r1body, rectBody, r1body.getWorldCenter()); physicsWorld.createJoint(r1jointDef); Rectangle r2 = new Rectangle(1132, 1300, 136, 150, getVertexBufferObjectManager()); r2.setColor(0, 1, 0, 0.5f); r2.setVisible(true); scene.attachChild(r2); Body r2body = PhysicsFactory.createBoxBody(physicsWorld, r2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.001f, 0.01f)); r2body.setUserData("suspensionHelper"); physicsWorld.registerPhysicsConnector(new PhysicsConnector(r2, r2body, true, true)); WeldJointDef r2jointDef = new WeldJointDef(); r2jointDef.initialize(r2body, rectBody, r2body.getWorldCenter()); physicsWorld.createJoint(r2jointDef); Rectangle r3 = new Rectangle(1298, 1300, 50, 150, getVertexBufferObjectManager()); r3.setColor(0, 1, 0, 0.5f); r3.setVisible(true); scene.attachChild(r3); Body r3body = PhysicsFactory.createBoxBody(physicsWorld, r3, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(1f, 0.01f, 0.01f)); r3body.setUserData("suspensionHelper"); physicsWorld.registerPhysicsConnector(new PhysicsConnector(r3, r3body, true, true)); WeldJointDef r3jointDef = new WeldJointDef(); r3jointDef.initialize(r3body, rectBody, r3body.getWorldCenter()); physicsWorld.createJoint(r3jointDef); MouseJointDef md = new MouseJointDef(); Sprite wheel1 = new Sprite( miniRect1.getX()+miniRect1.getWidth()/2-wheelTexture.getWidth()/2, miniRect1.getY()+miniRect1.getHeight()-wheelTexture.getHeight()/2, wheelTexture, engine.getVertexBufferObjectManager()); scene.attachChild(wheel1); Body wheel1body = PhysicsFactory.createCircleBody( physicsWorld, wheel1, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 5.0f)); wheel1body.setUserData("wheel"); Shape wheel1shape = wheel1body.getFixtureList().get(0).getShape(); wheel1shape.setRadius(wheel1shape.getRadius()*(3.0f/4.0f)); physicsWorld.registerPhysicsConnector(new PhysicsConnector(wheel1, wheel1body, true, true)); Sprite wheel2 = new Sprite( miniRect2.getX()+miniRect2.getWidth()/2-wheelTexture.getWidth()/2, miniRect2.getY()+miniRect2.getHeight()-wheelTexture.getHeight()/2, wheelTexture, engine.getVertexBufferObjectManager()); scene.attachChild(wheel2); Body wheel2body = PhysicsFactory.createCircleBody( physicsWorld, wheel2, BodyDef.BodyType.DynamicBody, PhysicsFactory.createFixtureDef(10.0f, 0.01f, 5.0f)); wheel2body.setUserData("wheel"); Shape wheel2shape = wheel2body.getFixtureList().get(0).getShape(); wheel2shape.setRadius(wheel2shape.getRadius()*(3.0f/4.0f)); physicsWorld.registerPhysicsConnector(new PhysicsConnector(wheel2, wheel2body, true, true)); RevoluteJointDef frontWheelRevoluteJointDef = new RevoluteJointDef(); frontWheelRevoluteJointDef.initialize(wheel1body, miniRect1Body, wheel1body.getWorldCenter()); frontWheelRevoluteJointDef.collideConnected = false; RevoluteJointDef rearWheelRevoluteJointDef = new RevoluteJointDef(); rearWheelRevoluteJointDef.initialize(wheel2body, miniRect2Body, wheel2body.getWorldCenter()); rearWheelRevoluteJointDef.collideConnected = false; rearWheelRevoluteJointDef.motorSpeed = 2050; rearWheelRevoluteJointDef.maxMotorTorque= 3580; physicsWorld.createJoint(frontWheelRevoluteJointDef); Joint j = physicsWorld.createJoint(rearWheelRevoluteJointDef); rearWheelRevoluteJoint = (RevoluteJoint)j; r1body.setBullet(true); r2body.setBullet(true); r3body.setBullet(true); miniRect1Body.setBullet(true); miniRect2Body.setBullet(true); rectBody.setBullet(true); at low speeds, it's OK, but on high speed vehicle can even flip around on flat ground.. Is there a way to make this work better?

    Read the article

  • Cocos2d Box2d how to shoot an object inside the screen

    - by Ahoura Ghotbi
    I have the code below : - (id) initWithGame:(mainGame*)game { if ((self = [super init])) { isTouchEnabled_ = YES; self.game = game; CGSize size = [[CCDirector sharedDirector] winSize]; screenH = size.height; screenW = size.width; character = [CCSprite spriteWithFile:@"o.png"]; character.position = ccp( size.width /2 , size.height/2 ); character.contentSize = CGSizeMake(72, 79); [self addChild:character z:10 tag:1]; _body = NULL; _radius = 14.0f; // Create ball body and shape b2BodyDef ballBodyDef; ballBodyDef.type = b2_dynamicBody; ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO); ballBodyDef.userData = character; _body = _game.world->CreateBody(&ballBodyDef); b2CircleShape circle; circle.m_radius = 26.0/PTM_RATIO; b2FixtureDef ballShapeDef; ballShapeDef.shape = &circle; ballShapeDef.density = 1.0f; ballShapeDef.friction = 0.2f; ballShapeDef.restitution = 0.8f; _body->CreateFixture(&ballShapeDef); [self schedule:@selector(gameChecker:)]; [self schedule:@selector(tick:)]; } return self; } - (void)gameChecker:(ccTime) dt{ if(character.position.y > 200){ [self unschedule:@selector(tick:)]; [self schedule:@selector(dropObject:)]; } } - (void)tick:(ccTime) dt { b2Vec2 force; force.Set(_body->GetLinearVelocity().x, _body->GetLinearVelocity().y+1.0f); for (b2Body* b = _game.world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() == character) { b->SetLinearVelocity(force); } } _game.world->Step(dt, 10, 10); for(b2Body *b = _game.world->GetBodyList(); b; b=b->GetNext()) { if (b->GetUserData() != NULL) { CCSprite *ballData = (CCSprite *)b->GetUserData(); ballData.position = ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO); ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()); } } } -(void)dropObject:(ccTime) dt{ b2Vec2 force; force.Set(_body->GetLinearVelocity().x, _body->GetLinearVelocity().y-1.0f); for (b2Body* b = _game.world->GetBodyList(); b; b = b->GetNext()) { if (b->GetUserData() == character) { b->SetLinearVelocity(force); } } _game.world->Step(dt, 10, 10); for(b2Body *b = _game.world->GetBodyList(); b; b=b->GetNext()) { if (b->GetUserData() != NULL) { CCSprite *ballData = (CCSprite *)b->GetUserData(); ballData.position = ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO); ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()); } } } I have been trying to get the effect that fruit ninja has when shooting the fruits. but it seems like its hard to get such animation so I was wondering if anyone can point me to the right direction and/or give me a sample code for a single object that gets thrown into the screen with a direction.

    Read the article

  • box2d resize bodies arround point

    - by philipp
    I have a compound object, consisting of a b2Body, vector-graphics and a list polygons which describe the b2body's shapes. This object has its own transformation matrix to centralize the storage of transformations. So far everything is working quiet fine, even scaling works, but not if i scale around a point. In the initialization phase of the object it is scaled around a point. This happens in this order: transform the main matrix transform the vector graphics and the polygons recreate the b2Body After this function ran, the shapes and all the graphics are exactly where they should be, BUT: after the first steps of the b2World the graphical stuff moves away from the body. When I ran the debugger I found out that the position of the body is 0/0 the red dot shows the center of scaling. the first image shows the basic setup and the second the final position of the graphics. This distance stays constant for the rest of the simulation. If I set the position via myBody.SetPosition( sx, sy ); the whole scenario just plays a bit more distant for the origin. Any Idea how to fix this? EDIT:: I came deeper down to the problem and it lies in the fact that i must not scale the transform matrix for the b2body shapes around the center, but set the b2body's position back to the point after scaling. But how can I calculate that point? EDIT 2 :: I came ever deeper down to it, even solved it, but this is a slow solution and i hope that there is somebody who understands what formula I need. assuming to have a set polygons relative to an origin as basis shapes for a b2body: scaling the whole object around a certain point is done in the following steps: i scale everything around the center except the polygons i create a clone of the polygons matrix i scale this clone around the point i calculate dx, dy as difference of clone.tx - original.tx and clone.ty - original.ty i scale the original polygon matrix NOT around the point i recreate the body i create the fixture i set the position of the body to dx and dy done! So what i an interested in is a formula for dx and dy without cloning matrices, scaling the clone around a point, getting dx and dy and finally scale the vertex matrix.

    Read the article

  • Box2D how to implement a camera?

    - by Romeo
    By now i have this Camera class. package GameObjects; import main.Main; import org.jbox2d.common.Vec2; public class Camera { public int x; public int y; public int sx; public int sy; public static final float PIXEL_TO_METER = 50f; private float yFlip = -1.0f; public Camera() { x = 0; y = 0; sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public Camera(int x, int y) { this.x = x; this.y = y; sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public void update() { sx = x + Main.APPWIDTH; sy = y + Main.APPHEIGHT; } public void moveCam(int mx, int my) { if(mx >= 0 && mx <= 80) { this.x -= 2; } else if(mx <= Main.APPWIDTH && mx >= Main.APPWIDTH - 80) { this.x += 2; } if(my >= 0 && my <= 80) { this.y += 2; } else if(my <= Main.APPHEIGHT && my >= Main.APPHEIGHT - 80) { this.y -= 2; } this.update(); } public float meterToPixel(float meter) { return meter * PIXEL_TO_METER; } public float pixelToMeter(float pixel) { return pixel / PIXEL_TO_METER; } public Vec2 screenToWorld(Vec2 screenV) { return new Vec2(screenV.x + this.x, yFlip * screenV.y + this.y); } public Vec2 worldToScreen(Vec2 worldV) { return new Vec2(worldV.x - this.x, yFlip * worldV.y - this.y); } } I need to know how to modify the screenToWorld and worldToScreen functions to include the PIXEL_TO_METER scaling.

    Read the article

  • Box2D `ApplyLinearImpulse` is not working whereas `SetLinearVelocity` works

    - by Narek
    I need to mimic jumping behavior for the player in my game. Player consists of two fixtures with circle and rectangle shapes. Rectangle I use to detect ground and it is a sensor. Is some point for jumping I do this: float impulseY = body->GetMass() * PLAYER_JUMPING_VEOCITY / PTM_RATIO * std::sin(PLAYER_JUMPING_ANGLE * PI / 180); body->ApplyLinearImpulse(b2Vec2(0, impulseY), body->GetWorldCenter(), true); and player does not jump. But when I do this: body->SetLinearVelocity(b2Vec2(0, PLAYER_JUMPING_VEOCITY / PTM_RATIO * std::sin(PLAYER_JUMPING_ANGLE * PI / 180))); my player jumps. Also when I change the rectangle shape to be normal (not sensor) shape, its works again. Why? Just in case here are the parameters of my rectangular sensor: b2PolygonShape boxShape; boxShape.SetAsBox(width * 0.5/2/PTM_RATIO, height * 0.2/2/PTM_RATIO, b2Vec2(0, -height * 0.4 /PTM_RATIO), 0); b2FixtureDef boxFixtureDef; boxFixtureDef.friction = 0; boxFixtureDef.restitution = 0; boxFixtureDef.density = 1; boxFixtureDef.isSensor = true; boxFixtureDef.userData = static_cast<void*>(PLAYER_GROUP);

    Read the article

  • Cocos2d Box2d contact listener call different method in collided object

    - by roma86
    I have the building object, wen it hit with other, i want to call some method inside it. Building.mm -(void)printTest { NSLog(@"printTest method work correctly"); } in my ContactListener i trying to call it so: ContactListener.mm #import "ContactListener.h" #import "Building.h" void ContactListener::BeginContact(b2Contact* contact) { b2Body* bodyA = contact->GetFixtureA()->GetBody(); b2Body* bodyB = contact->GetFixtureB()->GetBody(); Building *buildA = (Building *)bodyA->GetUserData(); Building *buildB = (Building *)bodyB->GetUserData(); if (buildB.tag == 1) { NSLog(@"tag == 1"); } if (buildA.tag == 2) { NSLog(@"tag == 2"); [buildA printTest]; } } NSLog(@"tag == 2"); work correctly, but [buildA printTest]; get error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CCSprite printTest]: unrecognized selector sent to instance 0x18595f0' Obviously I'm referring to the wrong object. How i can get different method and property in contacted objects from contactlistener class? Thanks.

    Read the article

  • Spawning bullets on command in Box2D

    - by recharge330
    I'm making a simple bullet hell game but I can't figure out how to get my character to shoot. Lets say I have bulletBody and shipBody, how would I continually spawn bulletBodies using the shipBody coordinates. I've tried a function that uses an array of b2bodies and just assigns them the bodydef and fixture but that causes the game to crash. C++ sample code would be best but any help is appreciated. EDIT: It looks like any reference to my b2World in a function will cause the game to crash. How do I declare the bodies without using a b2World as an argument in the function.

    Read the article

  • Confusing box2d forces

    - by Diken
    Hello Friends. This is my demo game screen-shoot. Here i am using three buttons. Right-bottom button is used for jump and left-bottom buttons used for move left and right. I have some questions 1) should i use linearImpuls for jump body?? 2) For move right and left which types of force i applied??? PLease tell me i am confusing to use linearImpuls, applyforce and linearVelocity. Thanks in advance

    Read the article

  • Box2d contant speed before and after collision

    - by bobenko
    I want to make my body fly at constant speed, how to make it fly at constant speed before and after collision? I set restitution of my body to 1.0 but after some direct and powerful collisions my objects begins to slow, I want it to fly same speed as before. I heard this can be done by setting liner damping of the object, I think it can prevent only from fast flying objects not slow. Thanks in advance.

    Read the article

  • EXC_BAD_ACCESS error when box2d joint is destroyed

    - by colilo
    When I destroy the weldJoint in the update method (see below) I get an EXC_BAD_ACCESS error pointing to the line world->DestroyJoint(weldJoint); in the update method below: -(void) update: (ccTime) dt { int32 velocityIterations = 8; int32 positionIterations = 1; // Instruct the world to perform a single step of simulation. It is // generally best to keep the time step and iterations fixed. world->Step(dt, velocityIterations, positionIterations); // using the iterator pos over the set std::set<BodyPair *>::iterator pos; for(pos = bodiesForJoints.begin(); pos != bodiesForJoints.end(); ++pos) { b2WeldJointDef weldJointDef; BodyPair *bodyPair = *pos; b2Body *bodyA = bodyPair->bodyA; b2Body *bodyB = bodyPair->bodyB; weldJointDef.Initialize(bodyA, bodyB, bodyA->GetWorldCenter()); weldJointDef.collideConnected = false; weldJoint = (b2WeldJoint*) world->CreateJoint(&weldJointDef); // Free the structure we allocated earlier. free(bodyPair); // Remove the entry from the set. bodiesForJoints.erase(pos); } for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) { if (b->GetUserData() != NULL) { CCSprite *mainSprite = (CCSprite*)b->GetUserData(); if (mainSprite.tag == 1) { mainSprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO); CGPoint mainSpritePosition = mainSprite.position; if (mainSprite.isMoved) { world->DestroyJoint(weldJoint); } } } } } In the HelloWorldLayer.h I set the weldJoint with the assign property. Am I destroying the joint in the wrong way? I would really appreciate any help. Thanks

    Read the article

  • Box2d world width and height ratio with screen width and height

    - by Sujith
    I have view, for example GameView which extends SurfaceView . I have integrated Box2D physics in GameView. I have two widths , GameView width, height and Box2D physics world width ,height. I need to get the position of box2d world with the GameView co-ordinates. For example, Total width of screen = 240 Total height of screen = 320 Screen points needed to be mapped onto box2d co-ordinates (x,y) = 127, 139 For this i need to get the max width and height of the Box2d physics world. Is there is any way to get the max width and height of Box2d world. or Can i limit the width and height of box2d world within the screen resolution.

    Read the article

  • Box 2d basic questions

    - by philipp
    I am a bit new to box2d and I am developing an game with type and letters. I am using an svg font and generate the box2d bodies direct from the glyphs path definition, using the convex hull of them. I also have an decomposition routine the decomposes this hull if necessary. All this it is more or less working, except that I got some strange errors which definitely are caused by the scale factors. The problem is caused by two factors: first: the world scale of box2d, second: the the precision of curve-approximation of the glyph vectors. So through scaling down the input vertices for box2d, it happens that they become equal caused by numerical precision, what causes errors in box2d. Through scaling the my glyphs a bit up, this goes away. I also goes away if I chose a different world scale factor, but this slows down the whole animation quite much! So if my view port is about 990px * 600px and i want to animate Glyphs in box2d which should have a size from about 50px * 50px up to 300px * 300px, which scale factor of the b2world should i choose? How small should the smallest distance from on vertex to another be, while approximating the glyph vectors? Thanks for help greetings philipp EDIT:: I continued reading the docs of box2d and after rethinking of the units system, which is designed to handle object from 0.1 up to 10 meters, I calculated a scale factor of 75. So Objects 600px width will are 8 meters wide in box2d and even small objects of about 20px width will become 0.26 meters width in box2d. I will go on trying with this values, but if there is somebody out there who could give me a clever advice i would be happy!

    Read the article

  • Only Integrating Box2D collision detection in my 2d engine?

    - by Mr.Gando
    I have integrated box2d in my engine, ( Debug Draw, etc. ) and with a world I can throw in some 2d squares/rectangles etc. I saw this post, where the user is basically not using a world for collision detection, however the user doesn't explain anything about how he's using the manifold (b2Manifold), etc. Another post, is in the cocos2d forum, ( scroll down to the user Lam in the third reply ) Could anyone help me a bit with this?, basically want to add collision detection without the need of using b2World ,etc etc. Thanks a lot!

    Read the article

  • Best strategy (tried and tested) for using Box2D in a real-time multiplayer game?

    - by Simon Grey
    I am currently tackling real-time multiplayer physics updates for a game engine I am writing. My question is how best to use Box2D for networked physics. If I run the simulation on the server, should I send position, velocity etc to every client on every tick? Should I send it every few ticks? Maybe there is another way that I am missing? How has this problem been solved using Box2D before? Anyone with some ideas would be greatly appreciated!

    Read the article

  • simple collision detection with box2dweb

    - by skywalker
    im beginner in box2dweb that version of box2d for javascript i wrote simple gravity system and i want to detect the collision between the box and the ground , when the falling box hit the ground execute simple function like function sucs(){alert("the box on the floor !")}; this is my code var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30; var b2Vec2 = Box2D.Common.Math.b2Vec2 , b2BodyDef = Box2D.Dynamics.b2BodyDef , b2Body = Box2D.Dynamics.b2Body , b2FixtureDef = Box2D.Dynamics.b2FixtureDef , b2Fixture = Box2D.Dynamics.b2Fixture , b2World = Box2D.Dynamics.b2World , b2MassData = Box2D.Collision.Shapes.b2MassData , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape , b2DebugDraw = Box2D.Dynamics.b2DebugDraw; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var world = new b2World(new b2Vec2(0, 8), true); var fixDef = new b2FixtureDef(); var bodyDef = new b2BodyDef(); fixDef.density = 1.0; fixDef.friction = 0.5; bodyDef.type = b2Body.b2_staticBody; fixDef.shape = new b2PolygonShape; fixDef.shape.SetAsBox(20, 2); bodyDef.position.Set(10, 400 / 30 + 1.8); world.CreateBody(bodyDef).CreateFixture(fixDef); fixDef.density = 1.0; fixDef.friction = 0.5; fixDef.restitution = 0.3; bodyDef.type = b2Body.b2_dynamicBody; bodyDef.position.Set(50 / SCALE, 0 / SCALE); //bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2); fixDef.shape = new b2PolygonShape(); fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE); world.CreateBody(bodyDef).CreateFixture(fixDef); var debugDraw = new b2DebugDraw(); debugDraw.SetSprite(document.getElementById("canvas").getContext("2d")); debugDraw.SetDrawScale(30.0); debugDraw.SetFillAlpha(0.5); debugDraw.SetLineThickness(1.0); debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit); world.SetDebugDraw(debugDraw); var image = new Image(); image.src = "image.png"; window.setInterval(gameLoop, 1000 / 60); function gameLoop() { world.Step(1 / 60, 8, 3); world.ClearForces(); context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); b = world.GetBodyList() var pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); b = b.GetNext(); pos = b.GetPosition(); context.save(); context.translate(pos.x * SCALE, pos.y * SCALE); //b.GetAngle()++; context.rotate(b.GetAngle()); context.drawImage(image, -25, -25); context.restore(); world.DrawDebugData(); };

    Read the article

  • How to set the position of a sprite within a box2d body?

    - by Frank
    Basically I have 2 polygons for my body. When I add a sprite for userData, the position of the texture isn't where I want it to be. What I want to do is adjust the position of the texture within the body. Here's the code sample of where I am setting this: CCSpriteSheet *sheet = (CCSpriteSheet*) [self getChildByTag:kTagSpriteSheet]; CCSprite *pigeonSprite = [CCSprite spriteWithSpriteSheet:sheet rect:CGRectMake(0,0,40,32)]; [sheet addChild:pigeonSprite z:0 tag:kPigeonSprite]; pigeonSprite.position = ccp( p.x, p.y); bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO); bodyDef.userData = sprite; b2Body *body = world->CreateBody(&bodyDef); b2CircleShape dynamicCircle; dynamicCircle.m_radius = .25f; dynamicCircle.m_p.Set(0.0f, 1.0f); // Define the dynamic body fixture. b2FixtureDef circleDef; circleDef.shape = &dynamicCircle; circleDef.density = 1.0f; circleDef.friction = 0.3f; body->CreateFixture(&circleDef); b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.0f); b2PolygonShape triangle; triangle.Set(vertices, 3); b2FixtureDef triangleDef1; triangleDef1.shape = &triangle; triangleDef1.density = 1.0f; triangleDef1.friction = 0.3f; body->CreateFixture(&triangleDef1);

    Read the article

  • How to optimize a box2d simulation in action game?

    - by nathan
    I'm working on an action game and i use box2d for physics. The game use a tiled map. I have different types of body: Static ones used for tiles Dynamic ones for player and enemies Actually i tested my game with ~150 bodies and i have a 60fps constantly on my computer but not on my mobile (android). The FPS drop as the number of body increase. After having profiled the android application, i saw that the World.step took around 8ms in CPU time to execute. Here are few things to note: Not all the world is visible on screen, i use a scrolling system Enemies are constantly moving toward the player so there is alaways to force applied to their body Enemies need to collide between each others Enemies collide with tiles I also now that i can active/desactive or sleep/awake bodies. Considering the fact that only a part of the enemies are possibly displayed on screen, is there any optimizations i can do to reduce the execution time of box2d simulation? I found a guy trying an optimization based on distance of enemies from the player (link). But i seems like he just desactives far bodies (in my case, i could desactive bodies that are not visible). But my enemies need to move even when they are not visible on screen, and applying forces will not workd on inactive bodies. Should i play with sleeping bodies here? Also, enemies are composed by two fixtures and are constantly colliding with each others and with tiles but i really never need to get notified about that. Is there anything i can do to optimize this kind of scenario? Finally, am i wrong to try to run simulation at 60FPS on mobile and should i try to make it run at 30FPS?

    Read the article

  • Friction in Box2d

    - by Rosarch
    I am using Box2d for a topdown game. The "ground" is a series of tiles, where each tile is a static body with a sensor shape. Can I make friction take effect for this, even though the objects aren't really "colliding" with the ground? If Box2d won't let me do this, I considered trying to implement my own by detecting what force is currently moving the object, and applying a force opposite to it, but I'm not quite sure how to detect that force.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >