Search Results

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

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

  • Which physics phenomenons can be simulated properly with Box2d or bullet physics? [on hold]

    - by user3585425
    Knowing that box2d or bullet physics can't simulate Newton's cradle (because of multiple bodies being in contact at the same time if I understand correctly), is there a sets of physics phenomenons that imply two or more objects that still can be simulated properly ? For example, I'm thinking about lightweight objects launched towards heavyweight objects. If the object is destroyed on contact, this would not make a difference if the energy is not transmitted correctly on impact.

    Read the article

  • Box2D blocky map. Body, Fixtures a huge map and performance

    - by Solom
    Right now I'm still in the planning phase of a my very first game. I'm creating a "Minecraft"-like game in 2D that features blocks that can be destroyed as well as players moving around the map. For creating the map I chose a 2D-Array of Integers that represent the Block ID. For testing purposes I created a huge map (16348 * 256) and in my prototype that didn't use Box2D everything worked like a charm. I only rendered those blocks that where within the bounds of my camera and got 60 fps straight. The problem started when I decided to use an existing physics-solution rather than implementing my own one. What I had was basically simple hitboxes around the blocks and then I had to manually check if the player collided with any of those in his neighborhood. For more advanced physics as well as the collision detection I want to switch over to Box2D. The problem I have right now is ... how to go about the bodies? I mean, the blocks are of a static bodytype. They don't move on their own, they just are there to be collided with. But as far as I can see it, every block needs his own body with a rectangular fixture attached to it, so as to be destroyable. But for a huge map such as mine, this turns out to be a real performance bottle-neck. (In fact even a rather small map [compared to the other] of 1024*256 is unplayable.) I mean I create thousands of thousands of blocks. Even if I just render those that are in my immediate neighborhood there are hundreds of them and (at least with the debugRenderer) I drop to 1 fps really quickly (on my own "monster machine"). I thought about strategies like creating just one body, attaching multiple fixtures and only if a fixture got hit, separate it from the body, create a new one and destroy it, but this didn't turn out quite as successful as hoped. (In fact the core just dumps. Ah hello C! I really missed you :X) Here is the code: public class Box2DGameScreen implements Screen { private World world; private Box2DDebugRenderer debugRenderer; private OrthographicCamera camera; private final float TIMESTEP = 1 / 60f; // 1/60 of a second -> 1 frame per second private final int VELOCITYITERATIONS = 8; private final int POSITIONITERATIONS = 3; private Map map; private BodyDef blockBodyDef; private FixtureDef blockFixtureDef; private BodyDef groundDef; private Body ground; private PolygonShape rectangleShape; @Override public void show() { world = new World(new Vector2(0, -9.81f), true); debugRenderer = new Box2DDebugRenderer(); camera = new OrthographicCamera(); // Pixel:Meter = 16:1 // Body definition BodyDef ballDef = new BodyDef(); ballDef.type = BodyDef.BodyType.DynamicBody; ballDef.position.set(0, 1); // Fixture definition FixtureDef ballFixtureDef = new FixtureDef(); ballFixtureDef.shape = new CircleShape(); ballFixtureDef.shape.setRadius(.5f); // 0,5 meter ballFixtureDef.restitution = 0.75f; // between 0 (not jumping up at all) and 1 (jumping up the same amount as it fell down) ballFixtureDef.density = 2.5f; // kg / m² ballFixtureDef.friction = 0.25f; // between 0 (sliding like ice) and 1 (not sliding) // world.createBody(ballDef).createFixture(ballFixtureDef); groundDef = new BodyDef(); groundDef.type = BodyDef.BodyType.StaticBody; groundDef.position.set(0, 0); ground = world.createBody(groundDef); this.map = new Map(20, 20); rectangleShape = new PolygonShape(); // rectangleShape.setAsBox(1, 1); blockFixtureDef = new FixtureDef(); // blockFixtureDef.shape = rectangleShape; blockFixtureDef.restitution = 0.1f; blockFixtureDef.density = 10f; blockFixtureDef.friction = 0.9f; } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); debugRenderer.render(world, camera.combined); drawMap(); world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS); } private void drawMap() { for(int a = 0; a < map.getHeight(); a++) { /* if(camera.position.y - (camera.viewportHeight/2) > a) continue; if(camera.position.y - (camera.viewportHeight/2) < a) break; */ for(int b = 0; b < map.getWidth(); b++) { /* if(camera.position.x - (camera.viewportWidth/2) > b) continue; if(camera.position.x - (camera.viewportWidth/2) < b) break; */ /* blockBodyDef = new BodyDef(); blockBodyDef.type = BodyDef.BodyType.StaticBody; blockBodyDef.position.set(b, a); world.createBody(blockBodyDef).createFixture(blockFixtureDef); */ PolygonShape rectangleShape = new PolygonShape(); rectangleShape.setAsBox(1, 1, new Vector2(b, a), 0); blockFixtureDef.shape = rectangleShape; ground.createFixture(blockFixtureDef); rectangleShape.dispose(); } } } @Override public void resize(int width, int height) { camera.viewportWidth = width / 16; camera.viewportHeight = height / 16; camera.update(); } @Override public void hide() { dispose(); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { world.dispose(); debugRenderer.dispose(); } } As you can see I'm facing multiple problems here. I'm not quite sure how to check for the bounds but also if the map is bigger than 24*24 like 1024*256 Java just crashes -.-. And with 24*24 I get like 9 fps. So I'm doing something really terrible here, it seems and I assume that there most be a (much more performant) way, even with Box2D's awesome physics. Any other ideas? Thanks in advance!

    Read the article

  • How to attach an object to a rotating circle in box2d cocos2d?

    - by armands
    I am trying to make an object get attached on a collision point to a circle that is rotating, but the player needs to get attached with a constant point on the player. For example the player is moving back and forth and when the user touches the screen and the player jumps up but what I need is that when the player collides with the circle it attaches it's legs to it and continues rotating with the circle. So I wanted to know how to make this kind of collision joint in cocos2d box2d?

    Read the article

  • Box2D in Flash runs quicker when drawing debug data than not

    - by bowdengm
    I've created a small game with Box2d for AS3 - I have sprites attached to the stage that take their position from the underlying Box2d world. These sprites are mostly PNGs. When the game runs with DrawDebugData() bening called every update, it runs nice and smoothly. However when I comment this out, it runs choppily. In both cases all my sprites are being rendered. So it seems that it's running faster when it's drawing the debug data additionaly (i.e. my sprites are on the screen in both cases!) What's going on? Does drawing the debug data flick some sort of 'render quick' switch? If so, what's the switch!? I can't see it in the Box2D code. function Update(e){ m_world.Step(m_timeStep, m_velocityIterations, m_positionIterations); // draw debug? m_world.DrawDebugData(); // with the above line in, I get 27fps, without it, I get 19fps. // that's the only change that's causing such a huge difference. doStuff(); } Interestingly, If i set the debug draw scale to something different to my world scale, it slows down to 19fps. So there's something happening when it draws the boxes under my sprites causing it to run quicker.. Cheers, Guy

    Read the article

  • RevoluteJoint Stop Rotating when Some Physics Body Collide in Andengine + Box2d?

    - by Nikhil Lamba
    I am making a Game from andengine + box2d in Which i am using RevoluteJoint in that case i am facing some problem that when physics body or Sprite Collide with this Revolute joint body then Revolute body stop rotating then after some time it start rotating I am using below code for this : this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true)); final RevoluteJointDef revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter()); revoluteJointDef.enableMotor = true; revoluteJointDef.motorSpeed = 100; revoluteJointDef.maxMotorTorque = 200; this.mPhysicsWorld.createJoint(revoluteJointDef); EDIT Here is a screenshot:

    Read the article

  • How do I duplicate a Box2d simulation, mid-simulation?

    - by Whyte
    I want to serialize the state mid-game, send it over the network to an identical computer (same CPU, same OS, same binary), load it there, and have the two games run in tandem doing the exact same simulation, without one of them drifting off and going haywire. In short: I want pop-in, pop-out networking support on my HIGHLY physics-intensive game, where sending object coordinates every few seconds is impossible, due to having thousands of objects, and many clients. I tried this with Box2D, and saving an object's location/velocity/etc wasn't enough... there's internal state that's not accessible through any public methods. My current workaround is to force EVERY client to save its entire worldstate and reload it from scratch, whenever a new player connects... but this is obviously bad practice, because it hangs the game for everyone whenever someone new connects. However, it works, with zero desynchronization. So, anyone know of any other techniques that can help me? Or should I just kiss my project goodbye?

    Read the article

  • Asking Box2d if a collision happened

    - by Rosarch
    I'm using Box2dx (ported to C#; optimized for XNA). It handles collision resolution, but how can I tell if two objects are currently colliding? This is the function I'm trying to write: public bool IsColliding(GameObjectController collider1, GameObjectController collider2) Where collider1.Model.Body is the Box2d Body, and collider1.Model.BodyDef is the Box2d BodyDef. (The same goes for collider2, of course.) UPDATE: Looks like contact listeners or this could be useful: AABB collisionBox; model.Body.GetFixtureList().GetAABB(out collisionBox); Why does GetFixtureList() return one fixture?

    Read the article

  • Problem Building dschaefer / android-box2d

    - by Qwark
    I'm trying to build dschaefer android-box2d, and did follow the recipe. I do get this error when trying to build the TestBox2d with eclipse: make all /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/bin/arm-eabi-ld \ -nostdlib -shared -Bsymbolic --no-undefined \ -o obj/libtest.so obj/test.o -L../box2d/lib/android -lbox2d \ -L/cygdrive/c/android/android-ndk-r3/build/platforms/android-3/arch-arm/usr/lib \ -llog -lc -lstdc++ -lm \ /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/lib/gcc/arm-eabi/4.2.1/interwork/libgcc.a \ /cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/bin/arm-eabi-ld: cannot find -lbox2d make: * [obj/libtest.so] Error 1 The only thing I did change was in the TestBox2d\Makefile where i did change the path to the NDK. There are some other that have the same problem HERE but I do not know how to fix it.

    Read the article

  • Level designing with Cocos2d and Box2d

    - by Majster
    I want to learn how to make levels using cocos2d and box2d (for iOS). I am talking about a 2d platformer such as Limbo or Braid or something like that. How can I design and build levels like this? I have seen Level Helper for cocos2d but its not free and I don't think it makes physic objects for box2d. How is this accomplished in real games? How to make camera move with character and so on. Any starting points would be much appreciated.

    Read the article

  • How to remove a box2d body when collision happens?

    - by Ayham
    I’m still new to java and android programming and I am having so much trouble Removing an object when collision happens. I looked around the web and found that I should never handle removing BOX2D bodies during collision detection (a contact listener) and I should add my objects to an arraylist and set a variable in the User Data section of the body to delete or not and handle the removing action in an update handler. So I did this: First I define two ArrayLists one for the faces and one for the bodies: ArrayList<Sprite> myFaces = new ArrayList<Sprite>(); ArrayList<Body> myBodies = new ArrayList<Body>(); Then when I create a face and connect that face to its body I add them to their ArrayLists like this: face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion); Body BoxBody = PhysicsFactory.createBoxBody(mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, BoxBody, true, true)); myFaces.add(face); myBodies.add(BoxBody); now I add a contact listener and an update handler in the onloadscene like this: this.mPhysicsWorld.setContactListener(new ContactListener() { private AnimatedSprite face2; @Override public void beginContact(final Contact pContact) { } @Override public void endContact(final Contact pContact) { } @Override public void preSolve(Contact contact,Manifold oldManifold) { } @Override public void postSolve(Contact contact,ContactImpulse impulse) { } }); scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { } }); My plan is to detect which two bodies collided in the contact listener by checking a variable from the user data section of the body, get their numbers in the array list and finally use the update handler to remove these bodies. The questions are: Am I using the arraylist correctly? How to add a variable to the User Data (the code please). I tried removing a body in this update handler but it still throws me NullPointerException , so what is the right way to add an update handler and where should I add it. Any other advices to do this would be great. Thanks in advance.

    Read the article

  • Box2d: Set active and inactive

    - by Rosarch
    I'm writing an XNA game in C# using the XNA port of Box2d - Box2dx. Entities like trees or zombies are represented as GameObjects. GameObjectManager adds and removes them from the game world: /// <summary> /// Does the work of removing the GameObject. /// </summary> /// <param name="controller">The GameObject to be removed.</param> private void removeGameObjectFromWorld(GameObjectController controller) { controllers.Remove(controller); worldState.Models.Remove(controller.Model); controller.Model.Body.SetActive(false); } public void addGameObjectToWorld(GameObjectController controller) { controllers.Add(controller); worldState.Models.Add(controller.Model); controller.Model.Body.SetActive(true); } controllers is a collection of GameObjectController instances. worldState.Models is a collection of GameObjectModel instances. When I remove GameObjects from Box2d this way, this method gets called: void IContactListener.EndContact(Contact contact) { GameObjectController collider1 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureA().GetBody()); GameObjectController collider2 = worldQueryUtils.gameObjectOfBody(contact.GetFixtureB().GetBody()); collisionRecorder.removeCollision(collider1, collider2); } worldQueryUtils: // this could be cached if we know bodies never change public GameObjectController gameObjectOfBody(Body body) { return worldQueryEngine.GameObjectsForPredicate(x => x.Model.Body == body).Single(); } This method throws an error: System.InvalidOperationException was unhandled Message="Sequence contains no elements" Source="System.Core" StackTrace: at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source) at etc Why is this happening? What can I do to avoid it? This method has been called many times before the body.SetActive() was called. I feel that this may be messing it up.

    Read the article

  • Box2d Cocos2d circle crash on contact with ground

    - by Oliver Cooper
    this is my first question here so sorry if I do something wrong or this is too long. I have been reading this tutorial by Ray Wenderlich, I have modified it so it is flatter and gradually goes down hill. Basically I have a ball roll down a bumpy hill, but at the moment the ball only drops from about 100 pixels above. When ever the touch the app crashes (the app is a Mac Cocos2d Box2d app). The ball code is this: CGSize winSize = [CCDirector sharedDirector].winSize; self.oeva = [CCSprite spriteWithTexture:[[CCTextureCache sharedTextureCache] addImage:@"Ball.png"]rect:CGRectMake(0, 0, 64, 64)]; _oeva.position = CGPointMake(68, winSize.height/2); [self addChild:_oeva z:1]; b2BodyDef oevaBodyDef; oevaBodyDef.type = b2_dynamicBody; oevaBodyDef.position.Set(68/PTM_RATIO, (winSize.height/2)/PTM_RATIO); // oevaBodyDef.userData = _oeva; _oevaBody = world->CreateBody(&oevaBodyDef); b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(60/PTM_RATIO, 400/PTM_RATIO); bodyDef.userData = _oeva; b2Body *body = world->CreateBody(&bodyDef); // Define another box shape for our dynamic body. b2CircleShape dynamicBox; dynamicBox.m_radius = 70/PTM_RATIO;//These are mid points for our 1m box // Define the dynamic body fixture. b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; body->CreateFixture(&fixtureDef); That works fine. This is the terrain code, this also works fine: -(void)generateTerrainWithWorld: (b2World *) inputWorld: (int) hillSize;{ b2BodyDef bd; bd.position.Set(0, 0); body = inputWorld->CreateBody(&bd); b2PolygonShape shape; b2FixtureDef fixtureDef; currentSlope = 0; CGSize winSize = [CCDirector sharedDirector].winSize; float xf = 0; float yf = (arc4random() % 10)+winSize.height/3; int x = 200; for(int i = 0; i < maxHillPoints; ++i) { hillPoints[i] = CGPointMake(xf, yf); xf = xf+ (arc4random() % x/2)+x/2; yf = ((arc4random() % 30)+winSize.height/3)-currentSlope; currentSlope +=10; } int hSegments; for (int i=0; i<maxHillPoints-1; i++) { CGPoint p0 = hillPoints[i-1]; CGPoint p1 = hillPoints[i]; hSegments = floorf((p1.x-p0.x)/cosineSegmentWidth); float dx = (p1.x - p0.x) / hSegments; float da = M_PI / hSegments; float ymid = (p0.y + p1.y) / 2; float ampl = (p0.y - p1.y) / 2; CGPoint pt0, pt1; pt0 = p0; for (int j = 0; j < hSegments+1; ++j) { pt1.x = p0.x + j*dx; pt1.y = ymid + ampl * cosf(da*j); fullHillPoints[fullHillPointsCount++] = pt1; pt0 = pt1; } } b2Vec2 p1v, p2v; for (int i=0; i<fullHillPointsCount-1; i++) { p1v = b2Vec2(fullHillPoints[i].x/PTM_RATIO,fullHillPoints[i].y/PTM_RATIO); p2v = b2Vec2(fullHillPoints[i+1].x/PTM_RATIO,fullHillPoints[i+1].y/PTM_RATIO); shape.SetAsEdge(p1v, p2v); body->CreateFixture(&shape, 0); } } However when ever the two collide the app crashes. The crash error is: Thread 6 CVDisplayLink: Program received signal: "SIGABRT" The error occurs on line 96 of b2ContactSolver.cpp: b2Assert(kNormal > b2_epsilon); The error log is: Assertion failed: (kNormal 1.19209290e-7F), function b2ContactSolver, file /Users/coooli01/Documents/Xcode Projects/Cocos2d/Hill Slide/Hill Slide/libs/Box2D/Dynamics/Contacts/b2ContactSolver.cpp, line 96. Sorry if I rambled on for too long, i've been stuck on this for ages.

    Read the article

  • Box2d: Maximum possible linear velocity?

    - by Rosarch
    I think I've configured Box2d to have some sort of maximum velocity for any body, but I'm not sure. I apply an impulse like (100000000, 100000000), and the body moves just as fast as (100, 100) - which is not that fast at all. My game is a top-down 2d. Here is some code that may be relevant: private readonly Vector2 GRAVITY = new Vector2(0, 0); public void initializePhysics(ContactReporter contactReporter) { world = new World(GRAVITY, true); IContactListener contactListener = contactReporter; world.ContactListener = contactListener; } public void Update(GameTime gameTime) { // ... worldState.PhysicsWorld.Step((float)gameTime.ElapsedGameTime.TotalSeconds, 10, 10); //... }

    Read the article

  • Box2d Documentation - Outdated, any better api refs?

    - by GONeale
    Hi guys, I am working with cocos2d + box2d and as I look through the 'Hello World' tutorial and attempt others I am finding many constructs which do not seem to be documented in the latest api ref. Would anybody be able to shed some light on what's going on? or point me in the right direction to someone who has covered the new constructs such as b2PolygonDef changing to b2PolygonShape and likewise for circle + who knows what else, seems there has not been any doc updates since August '09. This is the only information I could find on the issue, of another user stating they have found many mismatches also. http://www.cocos2d-iphone.org/forum/topic/1683

    Read the article

  • How do I prevent other dynamic bodies from affecting the player's velocity with Box2D?

    - by Milo
    I'm working on my player object for my game. PhysicsBodyDef def; def.fixedRotation = true; def.density = 1.0f; def.position = Vec2(200.0f, 200.0f); def.isDynamic = true; def.size = Vec2(50.0f,200.0f); m_player.init(def,&m_physicsEngine.getWorld()); This is how he moves: b2Vec2 vel = getBody()->GetLinearVelocity(); float desiredVel = 0; if (m_keys[ALLEGRO_KEY_A] || m_keys[ALLEGRO_KEY_LEFT]) { desiredVel = -5; } else if (m_keys[ALLEGRO_KEY_D] || m_keys[ALLEGRO_KEY_RIGHT]) { desiredVel = 5; } else { desiredVel = 0; } float velChange = desiredVel - vel.x; float impulse = getBody()->GetMass() * velChange; //disregard time factor getBody()->ApplyLinearImpulse( b2Vec2(impulse,0), getBody()->GetWorldCenter(),true); This creates a few problems. First, to move the player at a constant speed he must be given a high velocity. The problem with this is if he just comes in contact with a small box, he makes it move a lot. Now, I can fix this by lowering his density, but then comes my main issue: I need other objects to be able to run into him, but when they do, he should be like a static wall and not move. I'm not sure how to do that without high density. I cannot use collision groups since I still need him to be solid toward other dynamic things. How can this be done? Essentially, how do I prevent other dynamic bodies from affecting the player's velocity?

    Read the article

  • How do I implement smooth movement in a Box2D platform game?

    - by Romeo
    I have implemented a character in JBox2D which moves with the help of a wheel rotating at the bottom of it. The movement is the best result I've had 'till now but it's a little glitchy when the character stands on the edge. So I am thinking should I use five smaller wheels instead of a big wheel. The wheel/wheels will not be visible in the finished product, now they are drawn for debugging. Here is a video. Is there a better way to do this using JBox2D?

    Read the article

  • Box2D platformer movement. Should i mess with velocity?

    - by Romeo
    I have a platformer game in which I implemented the movement using a wheel attached to the hero. For jumping I use this: player.body.applyLinearImpulse(new Vec2(0, 30000000), player.body.getPosition()); The problem is that the xVelocity doesn't remain the same during the jump so it isn't looking natural. Is there any way to modify only the x velocity of the body so that before jumping I store it in a variable and after jumping I apply it to the body? I hope you understand what I am trying to say.

    Read the article

  • Box2D platformer movement. Are joints a good idea?

    - by Romeo
    So i smashed my brains trying to make my character move. As i wanted later in the game to add explosions and bullets it wasn't a good idea to mess with the velocity and the forces/impulses didn't work as i expected so something stuck in my mind: Is it a good idea to put at his bottom a wheel(circle) which is invisible to the player that will do the movement by rotation? I will attach this to my main body with a revolute joint but i don't really know how to make the main body and wheel body to don't collide one with each other since funny things can happen. What is your oppinion?

    Read the article

  • How to get local point inside a body where mouse click occurred in box2d?

    - by humbleBee
    I need to find out the point inside a body, lets say a rectangular object, where the mouse was clicked on. I'm makin a game where the force will be applied depending on where the mouse was clicked on the body. Any ideas? Will body.GetLocalPoint(b2vec2) work? I tried by passing the mouse coordinates when the click occurred when inside the body but if the body's position is (400,300) in world coordinates then for trace(body.GetLocalPoint(new b2vec2(mouseX,mouseY)).x); I get some value between 380 to 406 or something (eg. 401.6666666). I thought getLocalPoint will give something like x=-10 when clicked to the left of the centre of body or x=15 when clicked to the right. Language is As3 btw.

    Read the article

  • physics game programming box2d - orientating a turret-like object using torques

    - by egarcia
    This is a problem I hit when trying to implement a game using the LÖVE engine, which covers box2d with Lua scripting. The objective is simple: A turret-like object (seen from the top, on a 2D environment) needs to orientate itself so it points to a target. The turret is on the x,y coordinates, and the target is on tx, ty. We can consider that x,y are fixed, but tx, ty tend to vary from one instant to the other (i.e. they would be the mouse cursor). The turret has a rotor that can apply a rotational force (torque) on any given moment, clockwise or counter-clockwise. The magnitude of that force has an upper limit called maxTorque. The turret also has certain rotational inertia, which acts for angular movement the same way mass acts for linear movement. There's no friction of any kind, so the turret will keep spinning if it has an angular velocity. The turret has a small AI function that re-evaluates its orientation to verify that it points to the right direction, and activates the rotator. This happens every dt (~60 times per second). It looks like this right now: function Turret:update(dt) local x,y = self:getPositon() local tx,ty = self:getTarget() local maxTorque = self:getMaxTorque() -- max force of the turret rotor local inertia = self:getInertia() -- the rotational inertia local w = self:getAngularVelocity() -- current angular velocity of the turret local angle = self:getAngle() -- the angle the turret is facing currently -- the angle of the like that links the turret center with the target local targetAngle = math.atan2(oy-y,ox-x) local differenceAngle = _normalizeAngle(targetAngle - angle) if(differenceAngle <= math.pi) then -- counter-clockwise is the shortest path self:applyTorque(maxTorque) else -- clockwise is the shortest path self:applyTorque(-maxTorque) end end ... it fails. Let me explain with two illustrative situations: The turret "oscillates" around the targetAngle. If the target is "right behind the turret, just a little clock-wise", the turret will start applying clockwise torques, and keep applying them until the instant in which it surpasses the target angle. At that moment it will start applying torques on the opposite direction. But it will have gained a significant angular velocity, so it will keep going clockwise for some time... until the target will be "just behind, but a bit counter-clockwise". And it will start again. So the turret will oscillate or even go in round circles. I think that my turret should start applying torques in the "opposite direction of the shortest path" before it reaches the target angle (like a car braking before stopping). Intuitively, I think the turret should "start applying torques on the opposite direction of the shortest path when it is about half-way to the target objective". My intuition tells me that it has something to do with the angular velocity. And then there's the fact that the target is mobile - I don't know if I should take that into account somehow or just ignore it. How do I calculate when the turret must "start braking"?

    Read the article

  • Paddle Movement using Box2D

    - by Anubhav Sharma
    Hello everybody, I'm making a game like Arkanoid and to move the ship with mouse, I'm using the following code : var mousex:int = costume.stage.mouseX; if (mousex < paddleWidth/2) mousex = paddleWidth/2; else if (mousex > PhysiVals.STAGE_WIDTH - paddleWidth/2) mousex = PhysiVals.STAGE_WIDTH - paddleWidth / 2; var idealLocation:Point = new Point(mousex, ypos); var directionToTravel:b2Vec2 = new b2Vec2((idealLocation.x -> costume.x) * PhysiVals.paddleSpeed, idealLocation.y-costume.y); directionToTravel.Multiply(1 / PhysiVals.RATIO); directionToTravel.Multiply(30); body.SetLinearVelocity(directionToTravel); Everything's going fine there! The paddle is moving the way it should! The problem is I want a little inclination towards the direction its moving and when it stops moving the angle of inclination should become zero. I tried playing with the angular velocity but I have no real idea how to do this! So Please help!

    Read the article

  • Remove box2d bodies after collision deduction android?

    - by jubin
    Can any one explain me how to destroy box2d body when collide i have tried but my application crashed.First i have checked al collisions then add all the bodies in array who i want to destroy.I am trying to learning this tutorial My all the bodies are falling i want these bodies should destroy when these bodies will collide my actor monkey but when it collide it destroy but my aplication crashed.I have googled and from google i got the application crash reasons we should not destroy body in step funtion but i am removing body in the last of tick method. could any one help me or provide me code aur check my code why i am getting this prblem or how can i destroy box2d bodies. This is my code what i am doing. Please could any one check my code and tell me what is i am doing wrong for removing bodies. The code is for multiple box2d objects falling on my actor monkey it should be destroy when it will fall on the monkey.It is destroing but my application crahes. static class Box2DLayer extends CCLayer { protected static final float PTM_RATIO = 32.0f; protected static final float WALK_FACTOR = 3.0f; protected static final float MAX_WALK_IMPULSE = 0.2f; protected static final float ANIM_SPEED = 0.3f; int isLeft=0; String dir=""; int x =0; float direction; CCColorLayer objectHint; // protected static final float PTM_RATIO = 32.0f; protected World _world; protected static Body spriteBody; CGSize winSize = CCDirector.sharedDirector().winSize(); private static int count = 200; protected static Body monkey_body; private static Body bodies; CCSprite monkey; float animDelay; int animPhase; CCSpriteSheet danceSheet = CCSpriteSheet.spriteSheet("phases.png"); CCSprite _block; List<Body> toDestroy = new ArrayList<Body>(); //CCSpriteSheet _spriteSheet; private static MyContactListener _contactListener = new MyContactListener(); public Box2DLayer() { this.setIsAccelerometerEnabled(true); CCSprite bg = CCSprite.sprite("jungle.png"); addChild(bg,0); bg.setAnchorPoint(0,0); bg.setPosition(0,0); CGSize s = CCDirector.sharedDirector().winSize(); // Use scaled width and height so that our boundaries always match the current screen float scaledWidth = s.width/PTM_RATIO; float scaledHeight = s.height/PTM_RATIO; Vector2 gravity = new Vector2(0.0f, -30.0f); boolean doSleep = false; _world = new World(gravity, doSleep); // Create edges around the entire screen // Define the ground body. BodyDef bxGroundBodyDef = new BodyDef(); bxGroundBodyDef.position.set(0.0f, 0.0f); // The body is also added to the world. Body groundBody = _world.createBody(bxGroundBodyDef); // Register our contact listener // Define the ground box shape. PolygonShape groundBox = new PolygonShape(); Vector2 bottomLeft = new Vector2(0f,0f); Vector2 topLeft = new Vector2(0f,scaledHeight); Vector2 topRight = new Vector2(scaledWidth,scaledHeight); Vector2 bottomRight = new Vector2(scaledWidth,0f); // bottom groundBox.setAsEdge(bottomLeft, bottomRight); groundBody.createFixture(groundBox,0); // top groundBox.setAsEdge(topLeft, topRight); groundBody.createFixture(groundBox,0); // left groundBox.setAsEdge(topLeft, bottomLeft); groundBody.createFixture(groundBox,0); // right groundBox.setAsEdge(topRight, bottomRight); groundBody.createFixture(groundBox,0); CCSprite floorbg = CCSprite.sprite("grassbehind.png"); addChild(floorbg,1); floorbg.setAnchorPoint(0,0); floorbg.setPosition(0,0); CCSprite floorfront = CCSprite.sprite("grassfront.png"); floorfront.setTag(2); this.addBoxBodyForSprite(floorfront); addChild(floorfront,3); floorfront.setAnchorPoint(0,0); floorfront.setPosition(0,0); addChild(danceSheet); //CCSprite monkey = CCSprite.sprite(danceSheet, CGRect.make(0, 0, 48, 73)); //addChild(danceSprite); monkey = CCSprite.sprite("arms_up.png"); monkey.setTag(2); monkey.setPosition(200,100); BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.DynamicBody; spriteBodyDef.bullet=true; spriteBodyDef.position.set(200 / PTM_RATIO, 300 / PTM_RATIO); monkey_body = _world.createBody(spriteBodyDef); monkey_body.setUserData(monkey); PolygonShape spriteShape = new PolygonShape(); spriteShape.setAsBox(monkey.getContentSize().width/PTM_RATIO/2, monkey.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; monkey_body.createFixture(spriteShapeDef); //Vector2 force = new Vector2(10, 10); //monkey_body.applyLinearImpulse(force, spriteBodyDef.position); addChild(monkey,10000); this.schedule(tickCallback); this.schedule(createobjects, 2.0f); objectHint = CCColorLayer.node(ccColor4B.ccc4(255,0,0,128), 200f, 100f); addChild(objectHint, 15000); objectHint.setVisible(false); _world.setContactListener(_contactListener); } private UpdateCallback tickCallback = new UpdateCallback() { public void update(float d) { tick(d); } }; private UpdateCallback createobjects = new UpdateCallback() { public void update(float d) { secondUpdate(d); } }; private void secondUpdate(float dt) { this.addNewSprite(); } public void addBoxBodyForSprite(CCSprite sprite) { BodyDef spriteBodyDef = new BodyDef(); spriteBodyDef.type = BodyType.StaticBody; //spriteBodyDef.bullet=true; spriteBodyDef.position.set(sprite.getPosition().x / PTM_RATIO, sprite.getPosition().y / PTM_RATIO); spriteBody = _world.createBody(spriteBodyDef); spriteBody.setUserData(sprite); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; PolygonShape spriteShape = new PolygonShape(); spriteShape.set(verts); //spriteShape.setAsBox(sprite.getContentSize().width/PTM_RATIO/2, //sprite.getContentSize().height/PTM_RATIO/2); FixtureDef spriteShapeDef = new FixtureDef(); spriteShapeDef.shape = spriteShape; spriteShapeDef.density = 2.0f; spriteShapeDef.friction = 0.70f; spriteShapeDef.restitution = 0.0f; spriteShapeDef.isSensor=true; spriteBody.createFixture(spriteShapeDef); } public void addNewSprite() { count=0; Random rand = new Random(); int Number = rand.nextInt(10); switch(Number) { case 0: _block = CCSprite.sprite("banana.png"); break; case 1: _block = CCSprite.sprite("backpack.png");break; case 2: _block = CCSprite.sprite("statue.png");break; case 3: _block = CCSprite.sprite("pineapple.png");break; case 4: _block = CCSprite.sprite("bananabunch.png");break; case 5: _block = CCSprite.sprite("hat.png");break; case 6: _block = CCSprite.sprite("canteen.png");break; case 7: _block = CCSprite.sprite("banana.png");break; case 8: _block = CCSprite.sprite("statue.png");break; case 9: _block = CCSprite.sprite("hat.png");break; } int padding=20; //_block.setPosition(CGPoint.make(100, 100)); // Determine where to spawn the target along the Y axis CGSize winSize = CCDirector.sharedDirector().displaySize(); int minY = (int)(_block.getContentSize().width / 2.0f); int maxY = (int)(winSize.width - _block.getContentSize().width / 2.0f); int rangeY = maxY - minY; int actualY = rand.nextInt(rangeY) + minY; // Create block and add it to the layer float xOffset = padding+_block.getContentSize().width/2+((_block.getContentSize().width+padding)*count); _block.setPosition(CGPoint.make(actualY, 750)); _block.setTag(1); float w = _block.getContentSize().width; objectHint.setVisible(true); objectHint.changeWidth(w); objectHint.setPosition(actualY-w/2, 460); this.addChild(_block,10000); // Create ball body and shape BodyDef ballBodyDef1 = new BodyDef(); ballBodyDef1.type = BodyType.DynamicBody; ballBodyDef1.position.set(actualY/PTM_RATIO, 480/PTM_RATIO); bodies = _world.createBody(ballBodyDef1); bodies.setUserData(_block); PolygonShape circle1 = new PolygonShape(); Vector2 verts[] = { new Vector2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO), new Vector2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO), new Vector2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO), new Vector2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO), new Vector2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO), new Vector2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO), new Vector2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO) }; circle1.set(verts); FixtureDef ballShapeDef1 = new FixtureDef(); ballShapeDef1.shape = circle1; ballShapeDef1.density = 10.0f; ballShapeDef1.friction = 0.0f; ballShapeDef1.restitution = 0.1f; bodies.createFixture(ballShapeDef1); count++; //Remove(); } @Override public void ccAccelerometerChanged(float accelX, float accelY, float accelZ) { //Apply the directional impulse /*float impulse = monkey_body.getMass()*accelY*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); monkey_body.applyLinearImpulse(force, monkey_body.getWorldCenter());*/ walk(accelY); //Remove(); } private void walk(float accelY) { // TODO Auto-generated method stub direction = accelY; } private void Remove() { for (Iterator<MyContact> it1 = _contactListener.mContacts.iterator(); it1.hasNext();) { MyContact contact = it1.next(); Body bodyA = contact.fixtureA.getBody(); Body bodyB = contact.fixtureB.getBody(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (bodyA.getUserData() != null && bodyB.getUserData() != null) { CCSprite spriteA = (CCSprite) bodyA.getUserData(); CCSprite spriteB = (CCSprite) bodyB.getUserData(); // Is sprite A a cat and sprite B a car? If so, push the cat // on a list to be destroyed... if (spriteA.getTag() == 1 && spriteB.getTag() == 2) { //Log.v("dsfds", "dsfsd"+bodyA); //_world.destroyBody(bodyA); // removeChild(spriteA, true); toDestroy.add(bodyA); } // Is sprite A a car and sprite B a cat? If so, push the cat // on a list to be destroyed... else if (spriteA.getTag() == 2 && spriteB.getTag() == 1) { //Log.v("dsfds", "dsfsd"+bodyB); toDestroy.add(bodyB); } } } // Loop through all of the box2d bodies we want to destroy... for (Iterator<Body> it1 = toDestroy.iterator(); it1.hasNext();) { Body body = it1.next(); // See if there's any user data attached to the Box2D body // There should be, since we set it in addBoxBodyForSprite if (body.getUserData() != null) { // We know that the user data is a sprite since we set // it that way, so cast it... CCSprite sprite = (CCSprite) body.getUserData(); // Remove the sprite from the scene _world.destroyBody(body); removeChild(sprite, true); } // Destroy the Box2D body as well // _contactListener.mContacts.remove(0); } } public synchronized void tick(float delta) { synchronized (_world) { _world.step(delta, 8, 3); //_world.clearForces(); //addNewSprite(); } CCAnimation danceAnimation = CCAnimation.animation("dance", 1.0f); // Iterate over the bodies in the physics world Iterator<Body> it = _world.getBodies(); while(it.hasNext()) { Body b = it.next(); Object userData = b.getUserData(); if (userData != null && userData instanceof CCSprite) { //Synchronize the Sprites position and rotation with the corresponding body CCSprite sprite = (CCSprite)userData; if(sprite.getTag()==1) { //b.applyLinearImpulse(force, pos); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); sprite.setRotation(-1.0f * ccMacros.CC_RADIANS_TO_DEGREES(b.getAngle())); } else { //Apply the directional impulse float impulse = monkey_body.getMass()*direction*WALK_FACTOR; Vector2 force = new Vector2(impulse, 0); b.applyLinearImpulse(force, b.getWorldCenter()); sprite.setPosition(b.getPosition().x * PTM_RATIO, b.getPosition().y * PTM_RATIO); animDelay -= 1.0f/60.0f; if(animDelay <= 0) { animDelay = ANIM_SPEED; animPhase++; if(animPhase > 2) { animPhase = 1; } } if(direction < 0 ) { isLeft=1; } else { isLeft=0; } if(isLeft==1) { dir = "left"; } else { dir = "right"; } float standingLimit = (float) 0.1f; float vX = monkey_body.getLinearVelocity().x; if((vX > -standingLimit)&& (vX < standingLimit)) { // Log.v("sasd", "standing"); } else { } } } } Remove(); } } Sorry for my english. Thanks in advance.

    Read the article

  • Box2d too much for Circle/Circle collision detection?

    - by Joey Green
    I'm using cocos2d to program a game and am using box2d for collision detection. Everything in my game is a circle and for some reason I'm having a problem with some times things are not being detected as a collision when they should be. I'm thinking of rolling up my own collision detection since I don't think it would be too hard. Questions are: Would this approach work for collision detection between circles? a. get radius of circle A and circle B. b. get distance of the center of circle A and circle B c. if the distance is greater than or equal to the sum of circle A radius and circle B radius then we have a hit Should box2d be used for such simple collision detection? There are no physics in this game.

    Read the article

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