Search Results

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

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

  • Box2D Joints in entity components system

    - by Johnmph
    I search a way to have Box2D joints in an entity component system, here is what i found : 1) Having the joints in Box2D/Body component as parameters, we have a joint array with an ID by joint and having in the other body component the same joint ID, like in this example : Entity1 - Box2D/Body component { Body => (body parameters), Joints => { Joint1 => (joint parameters), others joints... } } // Joint ID = Joint1 Entity2 - Box2D/Body component { Body => (body parameters), Joints => { Joint1 => (joint parameters), others joints... } } // Same joint ID than in Entity1 There are 3 problems with this solution : The first problem is the implementation of this solution, we must manage the joints ID to create joints and to know between which bodies they are connected. The second problem is the parameters of joint, where are they got ? on the Entity1 or Entity2 ? If they are the same parameters for the joint, there is no problem but if they are differents ? The third problem is that we can't limit number of bodies to 2 by joint (which is mandatory), a joint can only link 2 bodies, in this solution, nothing prevents to create more than 2 entities with for each a body component with the same joint ID, in this case, how we know the 2 bodies to joint and what to do with others bodies ? 2) Same solution than the first solution but by having entities ID instead of Joint ID, like in this example : Entity1 - Box2D/Body component { Body => (body parameters), Joints => { Entity2 => (joint parameters), others joints... } } Entity2 - Box2D/Body component { Body => (body parameters), Joints => { Entity1 => (joint parameters), others joints... } } With this solution, we fix the first problem of the first solution but we have always the two others problems. 3) Having a Box2D/Joint component which is inserted in the entities which contains the bodies to joint (we share the same joint component between entities with bodies to joint), like in this example : Entity1 - Box2D/Body component { Body => (body parameters) } - Box2D/Joint component { Joint => (Joint parameters) } // Shared, same as in Entity2 Entity2 - Box2D/Body component { Body => (body parameters) } - Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity1 There are 2 problems with this solution : The first problem is the same problem than in solution 1 and 2 : We can't limit number of bodies to 2 by joint (which is mandatory), a joint can only link 2 bodies, in this solution, nothing prevents to create more than 2 entities with for each a body component and the shared joint component, in this case, how we know the 2 bodies to joint and what to do with others bodies ? The second problem is that we can have only one joint by body because entity components system allows to have only one component of same type in an entity. So we can't put two Joint components in the same entity. 4) Having a Box2D/Joint component which is inserted in the entity which contains the first body component to joint and which has an entity ID parameter (this entity contains the second body to joint), like in this example : Entity1 - Box2D/Body component { Body => (body parameters) } - Box2D/Joint component { Entity2 => (Joint parameters) } // Entity2 is the entity ID which contains the other body to joint, the first body being in this entity Entity2 - Box2D/Body component { Body => (body parameters) } There are exactly the same problems that in the third solution, the only difference is that we can have two differents joints by entity instead of one (by putting one joint component in an entity and another joint component in another entity, each joint referencing to the other entity). 5) Having a Box2D/Joint component which take in parameter the two entities ID which contains the bodies to joint, this component can be inserted in any entity, like in this example : Entity1 - Box2D/Body component { Body => (body parameters) } Entity2 - Box2D/Body component { Body => (body parameters) } Entity3 - Box2D/Joint component { Joint => (Body1 => Entity1, Body2 => Entity2, others parameters of joint) } // Entity1 is the ID of the entity which have the first body to joint and Entity2 is the ID of the entity which have the second body to joint (This component can be in any entity, that doesn't matter) With this solution, we fix the problem of the body limitation by joint, we can only have two bodies per joint, which is correct. And we are not limited by number of joints per body, because we can create an another Box2D/Joint component, referencing to Entity1 and Entity2 and put this component in a new entity. The problem of this solution is : What happens if we change the Body1 or Body2 parameter of Joint component at runtime ? We need to add code to sync the Body1/Body2 parameters changes with the real joint object. 6) Same as solution 3 but in a better way : Having a Box2D/Joint component Box2D/Joint which is inserted in the entities which contains the bodies to joint, we share the same joint component between these entities BUT the difference is that we create a new entity to link the body component with the joint component, like in this example : Entity1 - Box2D/Body component { Body => (body parameters) } // Shared, same as in Entity3 Entity2 - Box2D/Body component { Body => (body parameters) } // Shared, same as in Entity4 Entity3 - Box2D/Body component { Body => (body parameters) } // Shared, same as in Entity1 - Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity4 Entity4 - Box2D/Body component { Body => (body parameters) } // Shared, same as in Entity2 - Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity3 With this solution, we fix the second problem of the solution 3, because we can create an Entity5 which will have the shared body component of Entity1 and an another joint component so we are no longer limited in the joint number per body. But the first problem of solution 3 remains, because we can't limit the number of entities which have the shared joint component. To resolve this problem, we can add a way to limit the number of share of a component, so for the Joint component, we limit the number of share to 2, because we can only joint 2 bodies per joint. This solution would be perfect because there is no need to add code to sync changes like in the solution 5 because we are notified by the entity components system when components / entities are added to/removed from the system. But there is a conception problem : How to know easily and quickly between which bodies the joint operates ? Because, there is no way to find easily an entity with a component instance. My question is : Which solution is the best ? Is there any other better solutions ? Sorry for the long text and my bad english.

    Read the article

  • box2D simulation doesn't work

    - by shadow_of__soul
    has been a while since last time i used box2D, and i needed to make some stuff, and i saw that my simulation don't worked (compiles, but do anything). i haven't been able to even have working the examples or this simple example i'm pasting below: package { import flash.display.Sprite; import flash.events.Event; import Box2D.Common.Math.b2Vec2; import Box2D.Dynamics.b2World; import Box2D.Dynamics.b2BodyDef; import Box2D.Dynamics.b2Body; import Box2D.Collision.Shapes.b2CircleShape; import Box2D.Dynamics.b2Fixture; import Box2D.Dynamics.b2FixtureDef; import org.flashdevelop.utils.FlashConnect; import flash.events.TimerEvent; import flash.utils.Timer; public class Main extends Sprite { public var world:b2World; public var wheelBody:b2Body; public var stepTimer:Timer; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); var gravity:b2Vec2 = new b2Vec2(0, 10); world = new b2World(gravity, true); var wheelBodyDef:b2BodyDef = new b2BodyDef(); wheelBodyDef.type = b2Body.b2_dynamicBody; wheelBody = world.CreateBody(wheelBodyDef); var circleShape:b2CircleShape = new b2CircleShape(5); var wheelFixtureDef:b2FixtureDef = new b2FixtureDef(); wheelFixtureDef.shape = circleShape; var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef); stepTimer = new Timer(0.025 * 1000); stepTimer.addEventListener(TimerEvent.TIMER, onTick); FlashConnect.trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y); stepTimer.start(); // entry point } private function onTick(a_event:TimerEvent):void { world.Step(0.025, 10, 10); FlashConnect.trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y); } } } on this, the object should fall down, but the positions reported me by the trace method, are always 0. so is not a display problem, that i see everything freeze, is why the simulation is not working, and i have no idea why :( can anyone point me to the right direction of where i need to look for the problem? my settings are: windows 7 flashdevelop 4.2.1 SDK: 4.6.0 compiling for flash 10, but i tried every target i have available (till flash 11.5) project set at 30fps

    Read the article

  • 2D Procedural Terrain with box2d Assets

    - by Alex
    I'm making a game that invloves a tire moving through terrain that is generated randomly over 1000 points. The terrain is always a downwards incline like so: The actual box2d terrain extends one screen width behind and infront of the circular character. I'm now at a stage where I need to add gameplay elements to the terrain such as chasms or physical objects (like the demo polygon in the picture) and am not sure of the best way to structure the procedural generation of the terrain and objects. I currently have a very simple for loop like so: for(int i = 0; i < kMaxHillPoints; i++) { hillKeyPoints[i] = CGPointMake(terrainX, terrainY); if(i%50 == 0) { i += [self generateCasmAtIndex:i]; } terrainX += winsize.width/20; terrainY -= random() % ((int) winsize.height/20); } With the generateCasmAtIndex function add points to the hillKeyPoints array and incrementing the for loop by the required amount. If I want to generate box2d objects as well for specific terrain elements, I'll also have to keep track of the current position of the player and have some sort of array of box2d objects that need to be created at certain locations. I am not sure of an efficient way to accomplish this procedural generation of terrain elements with accompanying box2d objects. My thoughts are: 1) Have many functions for each terrain element (chasm, jump etc.) which add elements to be drawn to an array that is check on each game step - similar to what I've shown above. 2) Create an array of terrain element objects that string together and are looped over to create the terrain and generate the box2d objects. Each object would hold an array of points to be drawn and and array of accompanying box2d objects. Any help on this is much appreciated as I cannot see a 'clean' solution.

    Read the article

  • Determinism in multiplayer simulation with Box2D, and single computer

    - by Jake
    I wrote a small test car driving multiplayer game with Box2D using TCP server-client communcations. I ran 1 instance of server.exe and 2 instance of client.exe on the same machine that I code and compile the executables. I type inputs (WASD for a simple car movement) into one of the 2 clients and I can get both clients to update the simulation. There are 2 cars in the simulation. As long as the cars do not collide, I get the same identical output on both client.exe. I can run the car(s) around for as long as I could they still update the same. However, if I start to collide the cars, very quickly they go out of sync. My tools: Windows 7, C++, MSVS 2010, Box2D, freeGlut. My Psuedocode: // client.exe void timer(int value) { tcpServer.send(my_inputs); foreach(i = player including myself) inputs[i] = tcpServer.receive(); foreach(i = player including myself) players[i].process(inputs[i]); myb2World.step(33, 8, 6); // Box2D world step simulation foreach(i = player including myself) renderer.render(player[i]); glutTimerFunc(33, timer, 0); } // server.exe void serviceloop { while(all clients alive) { foreach(c = clients) tcpClients[c].receive(&inputs[c]); // send input of each client to all clients foreach(source = clients) { foreach(dest = clients) { tcpClients[dest].send(inputs[source]); } } } } I have read all over the internet and SE the following claims (paraphrased): Box2D is deterministic as long as floating point architecture/implementation is the same. (For any deterministic engine) Determinism is gauranteed if playback of recorded inputs is on the same machine with exe compiled using same compiler and machine. Additionally my server.exe and client.exe gameloop is single thread with blocking socket calls and fixed time step. Question: Can anyone explain what I did wrong to get different Box2D output?

    Read the article

  • AS3: StageWidth for BOX2D?

    - by Gabriel Meono
    I know BOX2D uses meters, and AS3 uses pixels. I'm trying to create objects which are limited to the stageWidth. If I do this variable: for (var i:int = 0; i<(stage.stageWidth); i++){...} The animation will freeze, and this output appears: TypeError: Error #1009: Cannot access a property or method of a null object reference. at Box2D.Collision::b2BroadPhase/CreateProxy() at Box2D.Collision.Shapes::b2Shape/CreateProxy() at Box2D.Dynamics::b2Body/CreateShape() at com.actionsnippet.qbox.objects::CircleObject/build() at com.actionsnippet.qbox::QuickObject/init() at com.actionsnippet.qbox::QuickObject() at com.actionsnippet.qbox.objects::CircleObject() at com.actionsnippet.qbox::QuickBox2D/create() at com.actionsnippet.qbox::QuickBox2D/addCircle() at BOX2D_Test_Tutorial_fla::MainTimeline/frame1() Does anyone know how to fix this? Full Code: [SWF(width = 350, height = 600, frameRate = 60)] import com.actionsnippet.qbox.*; var sim:QuickBox2D = new QuickBox2D(this); sim.createStageWalls(); // make a heavy circle sim.addCircle({x:3, y:3, radius:0.4, density:1}); // create a few platforms // make pins for (var i:int = 0; i<(stage.stageWidth); i++){ //End sim.addCircle({x:1 + i * 1.5, y:18, radius:0.1, density:0}); sim.addCircle({x:2 + i * 1.5, y:17, radius:0.1, density:0}); 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}); } sim.start(); sim.mouseDrag();

    Read the article

  • Are there any alternative JS ports of Box2D?

    - by Petteri Hietavirta
    I have been thinking about creating a top down 2D car game for HTML5. For my first game I wrote the physics and collisions my self but for this one I would like to use some ready made library. I found out Box2D and its JS port. http://box2d-js.sourceforge.net It seems to be quite old port, made in 2008. Is it lacking many features of current Box2D or does it have major issues with it? And are there any alternatives for it?

    Read the article

  • Check for bodies within a specific circle in Box2D

    - by ltjax
    I'm trying to find positions to insert new bodies into my world. For that, I'd like to have a "free" spot where this body wouldn't overlap with anything else. So my plan was to sample "random" positions and check whether they overlap with my "potential" new body. Since my bodies are always circular, I'd need to test within a given circle. So far, the only way to use box2d for this seems to use b2World::QueryAABB around my circle and manually doing an overlap test with all the fixtures it gives me (Box2D doesn't event seem to allow me to tap into its overlapping tests?!). It seems to me like Box2D should already provide such functionality - is there a way that lets me do this without reinventing most of the wheel again?

    Read the article

  • how can i move static box2d object.

    - by user5198
    how can i move static box2d sprites. i have tried this tutorial from . http://www.raywenderlich.com/475/how-to-create-a-simple-breakout-game-with-box2d-and-cocos2d-tutorial-part-12. I managed to add another "paddle" object with box2d body, but i can seam to be able to make the code to move the second "paddle" body. Can anyone direct me how to do it? Is there a way to move a "b2_staticBody" box 2d object? i have tried, but i can only move it when i use "b2_dynamicBody" if i used "b2_staticBody" i can move it at all.

    Read the article

  • Are there any alternative JS ports of Box2D?

    - by Petteri Hietavirta
    I have been thinking about creating a top down 2D car game for HTML5. For my first game I wrote the physics and collisions my self but for this one I would like to use some ready made library. I found out Box2D and its JS port. http://box2d-js.sourceforge.net It seems to be quite old port, made in 2008. Is it lacking many features of current Box2D or does it have major issues with it? And are there any alternatives for it?

    Read the article

  • cocos2d: syncing CCAnimation frames with Box2d Shape manipulations

    - by Hezi Cohen
    hi everybody! my cocos2d game currently has a ccsprite attached to a box2d body. during the game i apply different CCAnimations on my sprite, i would like to perform certain manipulations to the box2d body according to the frame currently displayed by the sprite (change rotation of the body, etc.) my current idea on implementing this is to subclass ccsprite and change the setDisplayFrame implementation but i thought somebody here probably did the same and already has a solution, so any suggestions on how to implement this? thanks!

    Read the article

  • Box2D networking

    - by spacevillain
    I am trying to make a simple sync between two box2d rooms, where you can drag boxes using the mouse. So every time player clicks (and holds the mousedown) a box, I try send joint parameters to server, and server sends them to other clients. When mouseup occurs, I send command to delete joint. The problem is that sync breaks too often. Is my way radically wrong, or it just needs some tweaks? http://www.youtube.com/watch?v=eTN2Gwj6_Lc Source code https://github.com/agentcooper/Box2d-networking

    Read the article

  • Box2D relations

    - by Valentino Ru
    As far as I know, the unit in Box2D is meters. When I use Box2D in Processing with JBox2D, I set the "world size" as the window size specified in the setup(). Now I'm wondering if there is any function that scales down the world. For example, how can I simulate the throw of tennis ball within a room, without using a window of only 5 x 5 pixels? Additionally, is there any good documentation like the Java API?

    Read the article

  • Box2D: How to get the Exact Collision Point and ignore the collision (from 2 "ghost bodies")

    - by Moritz
    I have a very basic problem with Box2D. For a arenatype game where you can throw scriptable "missiles" at other players I decided to use Box2D for the collision detection between the players and the missiles. Players and missiles have their own circular shape with a specific size (varying). But I don´t want to use dynamic bodies because the missiles need to move themselve in any way they want to (defined in the script) and shouldnt be resolved unless the script wants it. The behavior I look for is as following (for each time step): velocity of missiles is set by the specific missile script each missile is moved according to that velocity if a collision accurs now, I want to get the exact position of impact, and now I need a mechanism to decide if the missile should just ignore the collision (for example collision between two fireballs which shouldnt interact) or take it (so they are resolved and dont overlap anymore) So is there a way in Box2D to create Ghost bodies and listen to collisions from them, then deciding if they should ignore the collision or should take them and resolve their position? I hope I was clear enough and would be happy about any help!

    Read the article

  • How to create an extensible rope in Box2D?

    - by Thomas
    Let's say I'm trying to create a ninja lowering himself down a rope, or pulling himself back up, all whilst he might be swinging from side to side or hit by objects. Basically like http://ninja.frozenfractal.com/ but with Box2D instead of hacky JavaScript. Ideally I would like to use a rope joint in Box2D that allows me to change the length after construction. The standard Box2D RopeJoint doesn't offer that functionality. I've considered a PulleyJoint, connecting the other end of the "pulley" to an invisible kinematic body that I can control to change the length, but PulleyJoint is more like a rod than a rope: it constrains maximum length, but unlike RopeJoint it constrains the minimum as well. Re-creating a RopeJoint every frame using a new length is rather inefficient, and I'm not even sure it would work properly in the simulation. I could create a "chain" of bodies connected by RotationJoints but that is also less efficient, and less robust. I also wouldn't be able to change the length arbitrarily, but only by adding and removing a whole number of links, and it's not obvious how I would connect the remainder without violating existing joints. This sounds like something that should be straightforward to do. Am I overlooking something?

    Read the article

  • How to make Box2D bodies automatically return to a initial rotation

    - by sm4
    I have two long Box2D bodies, that can collide while moving one of them around with MouseJoint. I want them to try to hold their position and rotation. Blue body is moved using MouseJoint (yellow) towards the Red body. Red body has another MouseJoint - Blue can push Red, but Red will try to return to the start point thanks to the MouseJoint - this works just fine. Both bodies correctly rotate along the middle. This is still as I want. I change the MouseJoint to move the Blue away. What I need is both bodies return to their initial rotation (green arrows) Desired positions and rotations Is there anything in Box2D that could do this automatically? The MouseJoint does that nicely for position. I need it in AndEngine (Java, Android) port, but any Box2D solution is fine. EDIT: By automatically I mean having something I can add to the object "Paddle" without the need to change game loop. I want to encapsulate this functionality to the object itself. I already have an object Paddle that has its own UpdateHandler which is being called from the game loop. What would be much nicer is to attach some kind of "spring" joint to both left and right sides of the paddle that would automatically level the paddle. I will be exploring this option soon.

    Read the article

  • Running multiple box2D world objects on a server

    - by CharbelAbdo
    I'm creating a multiplayer game using LibGdx (with Box2d) and Kryonet. Since this is the first time I work on multiplayer games, I read a bit about server - client implementations, and it turns out that the server should handle important tasks like collision detection, hits, characters dying etc... Based on some articles (like the excellent Gabriel Gambetta Fast paced multiplayer series), I also know that the client should work in parallel to avoid the lag while the server responds to commands. Physics wise, each game will have 2 players, and any projectiles fired. What I'm thinking of doing is the following: Create a physics world on the client When the game is signaled to start, I create the same physics world on the server (without any rendering obviously). Whenever the player issues a command (move or fire), I send the command to the server and immediately start processing it on the client. When the server receives the command, it applies it on the server's world (set velocity etc...) Each 100ms, the server sends the new state to the client which corrects what was calculated locally. Any critical action (hit, death, level up) is calculated only on the server and sent to the client. Essentially, I would have a Box2d World object running on the server for each game in progress, in sync with the worlds running on the clients. The alternative would be to do my own calculations on the server instead of relying on Box2D to do them for me, but I'm trying to avoid that. My question is: Is it wise to have, for example, 1000 instances of the World object running and executing steps on the server? Tomcat used around 750 MBytes of memory when trying it without any object added to the world. Anybody tried that before? If not, is there any alternative? Google did not help me, are there any guidelines to use when you want to have physics on both the client and the server? Thanks for any help.

    Read the article

  • Understanding Box2d Restitution & Bouncing

    - by layzrr
    I'm currently trying to implement basketball bouncing into my game using Box2d (jBox2d technically), but I'm a bit confused about restitution. While trying to create the ball in the testbed first, I've run into infinite bouncing, as described in this question, however obviously not using my own implementation. The Box2d manual describes restitution as follows: Restitution is used to make objects bounce. The restitution value is usually set to be between 0 and 1. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. My confusion lies in that I am still getting infinite bouncing with restitution values at 0.75/0.8. The same behavior can be seen in the testbed under Collision Watching - Varying Restitution, on the 6th and 7th balls. I believe the last one has restitution of 1, which makes sense, but I don't understand why the second to last ball bounces infinitely (as is happening with my working basketball I've created). I am looking to understand the restitution concept more fully, as well as look for a solution to infinite bouncing with the Box2d framework. My instinct was to sleep objects that appeared to be moving in very small increments, but this seems like a misuse of the engine. Should I just work with lower restitution values altogether?

    Read the article

  • LibGDX Box2D Body and Sprite AND DebugRenderer out of sync

    - by Free Lancer
    I am having a couple issues with Box2D bodies. I have a GameObject holding a Sprite and Body. I use a ShapeRenderer to draw an outline of the Body's and Sprite's bounding boxes. I also added a Box2DDebugRenderer to make sure everything's lining up properly. My problem is the Sprite and Body at first overlap perfectly, but as I turn the Body moves a bit off the sprite then comes back when the Car is facing either North or South. Here's an image of what I mean: (Not sure what that line is, first time to show up) BLUE is the Body, RED is the Sprite, PURPLE is the Box2DDebugRenderer. Also, you probably noticed a purple square in the top right corner. Well that's the Car drawn by the Box2D Debug Renderer. I thought it might be the camera but I've been playing with the Cameras for hours and nothing seems to work. All give me weird results. Here's my code: Screen: public void show() { // --------------------- SETUP ALL THE CAMERA STUFF ------------------------------ // battleStage = new Stage( 720, 480, false ); // Setup the camera. In Box2D we operate on a meter scale, pixels won't do it. So we use // an Orthographic camera with a Viewport of 24 meters in width and 16 meters in height. battleStage.setCamera( new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT ) ); battleStage.getCamera().position.set( CAM_METER_WIDTH / 2, CAM_METER_HEIGHT / 2, 0 ); // The Box2D Debug Renderer will handle rendering all physics objects for debugging debugger = new Box2DDebugRenderer( true, true, true, true ); //debugCam = new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT ); } public void render(float delta) { // Update the Physics World, use 1/45 for something around 45 Frames/Second for mobile devices physicsWorld.step( 1/45.0f, 8, 3 ); // 1/45 for devices // Set the Camera matrices and clear the screen Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); battleStage.getCamera().update(); // Draw game objects here battleStage.act(delta); battleStage.draw(); // Again update the Camera matrices and call the debug renderer debugCam.update(); debugger.render( physicsWorld, debugCam.combined); // Vehicle handles its own interaction with the HUD // update all Actors movements in the game Stage hudStage.act( delta ); // Draw each Actor onto the Scene at their new positions hudStage.draw(); } Car: (extends Actor) public Car( Texture texture, float posX, float posY, World world ) { super( "Car" ); mSprite = new Sprite( texture ); mSprite.setSize( WIDTH * Consts.PIXEL_METER_RATIO, HEIGHT * Consts.PIXEL_METER_RATIO ); mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2); // set the origin to be at the center of the body mSprite.setPosition( posX * Consts.PIXEL_METER_RATIO, posY * Consts.PIXEL_METER_RATIO ); // place the car in the center of the game map FixtureDef carFixtureDef = new FixtureDef(); mBody = Physics.createBoxBody( BodyType.DynamicBody, carFixtureDef, mSprite ); } public void draw() { mSprite.setPosition( mBody.getPosition().x * Consts.PIXEL_METER_RATIO, mBody.getPosition().y * Consts.PIXEL_METER_RATIO ); mSprite.setRotation( MathUtils.radiansToDegrees * mBody.getAngle() ); // draw the sprite mSprite.draw( batch ); } Physics: (Create the Body) public static Body createBoxBody( final BodyType pBodyType, final FixtureDef pFixtureDef, Sprite pSprite ) { float pRotation = 0; float pWidth = pSprite.getWidth(); float pHeight = pSprite.getHeight(); final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; boxBodyDef.position.x = pSprite.getX() / Consts.PIXEL_METER_RATIO; boxBodyDef.position.y = pSprite.getY() / Consts.PIXEL_METER_RATIO; // Temporary Box shape of the Body final PolygonShape boxPoly = new PolygonShape(); final float halfWidth = pWidth * 0.5f / Consts.PIXEL_METER_RATIO; final float halfHeight = pHeight * 0.5f / Consts.PIXEL_METER_RATIO; boxPoly.setAsBox( halfWidth, halfHeight ); // set the anchor point to be the center of the sprite pFixtureDef.shape = boxPoly; final Body boxBody = BattleScreen.getPhysicsWorld().createBody(boxBodyDef); boxBody.createFixture(pFixtureDef); } Sorry for all the code and long description but it's hard to pin down what exactly might be causing the problem.

    Read the article

  • Rotating an object about a point (2D) using box2d

    - by noob
    i just started developing using box2d on flixel and i realise the pivot point of the rotation of an object in box2d is set to the center of an object. i had read on forums and i found out that SetAsBox can change the pivot point of the object, however, i cannot seem to get it work to rotate about a point. what i would like to achieve is to rotate an object about a point like earth revolving around the sun. any one can help me with it? really thanks a lot and sorry for the bad english

    Read the article

  • Increasing speed of circle over time as linear with Box2d

    - by Whispered
    Assume that there is a circle and it can be moved by using keyboard arrows.Is required that increasing speed over time like increasing car speed. For example; max speed is 25 and time to reach max speed shall be 5 sec. Over 5 sec the speed will reach to max speed. Does Box2d handle that situation?. I tried setting linear valocity but it seems to make the circle have constant speed instead of increased speed over time. Thank You! Note: I'm using Box2DWeb Javascript port of Box2D.

    Read the article

  • Detecting a ledge in Box2D

    - by DormoTheNord
    I'm making a 2D platformer with Box2D. The player needs to be able to grab onto a ledge and pull him/herself up. Right now I have a sensor that extends in every direction from the upper half of the player's body. The logic seems simple enough: if there are tiles inside the sensor and empty space above them, then it's a ledge and the game should act accordingly. The problem is that I can't figure out how to implement that logic with Box2D. Anyone have any ideas?

    Read the article

  • box2d and constant movement

    - by Arnas
    i'm developing a game with a top down view, the players body is a circle. To move the character you need to tap on the screen and it moves to the spot. To achieve this i'm saving the coordinate of the touch and call a method every frame which applies linear velocity to the body with a vector of the direction the body should go _body->SetLinearVelocity(b2Vec2((a.x - currPos.x)/SPEED_RATIO,(size.height - a.y - currPos.y)/SPEED_RATIO)); //click position - current position, screen height - click position (since the y axis is flipped, (0,0) is in the bottom left ) - current position = vector of the direction we want to go now the problem with this is that the body slows down until it finally stops when getting closer to the point we want it to go, since the closer we are to that point the lenght of the vector gets smaller. Besides that i've read that it's bad practice to set linear velocity in box2d and i should use apply force instead, but that way the forces would add up and overshoot the target where it's supposed to stop. So what i'm asking is how to move a box2d body to a coordinate in constant speed.

    Read the article

  • Communication between Box2D and libGDX Stage (Scene2D) running in separate threads

    - by atok
    I'm making a physics based 2D game using libGDX and Box2D. I want to move the execution of the simulation out of render thread. I use immutable messages and the BlockingQueue to pass the information about player actions. The Box2D applies forces and runs a frame of simulation. In the next step I would like to sync back the changes and update Scene2D Actors accordingly. Making an immutable copy of the state of the game world and sending it back using Gdx.app.postRunnable() is one option but it seems inefficient. Is there any other option?

    Read the article

  • Libgdx Box2d createfixture crashes vm intermittently

    - by user45021
    I have a hard to debug problem. I have a Box2D game which creates a wheeled vehicle. I want the vehicle body to reflect when it goes from moving left to moving right. to do this i set a flag in a changelistener on a button and then in update method i destroy and recreate the body facing the other way. it works fine most of the time but if i flip the vehicle several times quickly JVM crashes. no errors nothing in log. i added system.out.prints and the errors occur in the routine that instantiates the new body and before anything gets deleted/removed so i don't think the UI is trying to access null pointers. and if it was it should throw an error. M the crash seems to be at createFixture statements. but the work most of the first time. I tried debugging but the error doesn't happen much when the flips are slow. in any case createFixture drops fairly quickly into jni. Is this a Box2D bug? Is GC the issue? From Mission Control I see the GC is collecting on a period of ooh maybe 5s and flipping slower than that mostly works. how do i debug this? i am win7 64bit with 64bit at and jdk7 64bit. libgdx-0.9.9 and sometimes libgdx-nightly-20140215.

    Read the article

  • Pathfinding and BSP with Box2D

    - by Amplify91
    I'm looking into implementing AI in my 2D side-scrolling platformer, and I'm looking into using algorithms such as A*. For many kinds of pathfinding, we need some sort of grid or systems of nodes or polygon areas. My problem is that I am using Box2d for physics and I am not sure how best to create a structure that my AI can use besides placing individual nodes manually (something I really want to avoid) and using some sort of steering behavior. My level design is tile-based with each tile being about half of the height/width of my main character. The tiles are not all square (some are sloped). I'd like to have a system that can see what the terrain looks like for pathfinding and also keep track of the positions of other actors such as enemies. I'd like to avoid directly placing any nodes into my level design except for possible endpoints or goals. This question is related: How do you do AI path following within a 2d physics engine like farseer/box2d?, but it doesn't specify what kind of structure I could use instead of a list of nodes. I'm looking for some kind of grid or type of BSP that I can query for algorithms like A*.

    Read the article

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