Search Results

Search found 16 results on 1 pages for 'jbox2d'.

Page 1/1 | 1 

  • JBox2D Polygon Collisions Acting Strange

    - by andy
    I have been playing around with JBox2D and Slick2D and made a little demo with a ground object, a box object, and two different polygons. The problem I am facing is that the collision-detection for the polygons seems to be off (see picture below), but the box's collision works fine. My Code: Main Class package main; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.World; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import shapes.Box; import shapes.Polygon; public class State1 extends BasicGameState{ World world; int velocityIterations; int positionIterations; float pixelsPerMeter; int state; Box ground; Box box1; Polygon poly1; Polygon poly2; Renderer renderer; public State1(int state) { this.state = state; } @Override public void init(GameContainer gc, StateBasedGame game) throws SlickException { velocityIterations = 10; positionIterations = 10; pixelsPerMeter = 1f; world = new World(new Vec2(0.f, -9.8f)); renderer = new Renderer(gc, gc.getGraphics(), pixelsPerMeter, world); box1 = new Box(-100f, 200f, 40, 50, BodyType.DYNAMIC, world); ground = new Box(-14, -275, 50, 900, BodyType.STATIC, world); poly1 = new Polygon(50f, 10f, new Vec2[] { new Vec2(-6f, -14f), new Vec2(0f, -20f), new Vec2(6f, -14f), new Vec2(10f, 10f), new Vec2(-10f, 10f) }, BodyType.DYNAMIC, world); poly2 = new Polygon(0f, 10f, new Vec2[] { new Vec2(10f, 0f), new Vec2(20f, 0f), new Vec2(30f, 10f), new Vec2(30f, 20f), new Vec2(20f, 30f), new Vec2(10f, 30f), new Vec2(0f, 20f), new Vec2(0f, 10f) }, BodyType.DYNAMIC, world); } @Override public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException { world.step((float)delta / 180f, velocityIterations, positionIterations); } @Override public void render(GameContainer gc, StateBasedGame game, Graphics g) throws SlickException { renderer.render(); } @Override public int getID() { return this.state; } } Polygon Class package shapes; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; import org.newdawn.slick.Color; public class Polygon { public float x, y; public Color color; public BodyType bodyType; org.newdawn.slick.geom.Polygon poly; BodyDef def; PolygonShape ps; FixtureDef fd; Body body; World world; Vec2[] verts; public Polygon(float x, float y, Vec2[] verts, BodyType bodyType, World world) { this.verts = verts; this.x = x; this.y = y; this.bodyType = bodyType; this.world = world; init(); } public void init() { def = new BodyDef(); def.type = bodyType; def.position.set(x, y); ps = new PolygonShape(); ps.set(verts, verts.length); fd = new FixtureDef(); fd.shape = ps; fd.density = 2.0f; fd.friction = 0.7f; fd.restitution = 0.5f; body = world.createBody(def); body.createFixture(fd); } } Rendering Class package main; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.collision.shapes.ShapeType; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.World; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Transform; public class Renderer { World world; float pixelsPerMeter; GameContainer gc; Graphics g; public Renderer(GameContainer gc, Graphics g, float ppm, World world) { this.world = world; this.pixelsPerMeter = ppm; this.g = g; this.gc = gc; } public void render() { Body current = world.getBodyList(); Vec2 center = current.getLocalCenter(); while(current != null) { Vec2 pos = current.getPosition(); g.pushTransform(); g.translate(pos.x * pixelsPerMeter + (0.5f * gc.getWidth()), -pos.y * pixelsPerMeter + (0.5f * gc.getHeight())); Fixture f = current.getFixtureList(); while(f != null) { ShapeType type = f.getType(); g.setColor(getColor(current)); switch(type) { case POLYGON: { PolygonShape shape = (PolygonShape)f.getShape(); Vec2[] verts = shape.getVertices(); int count = shape.getVertexCount(); Polygon p = new Polygon(); for(int i = 0; i < count; i++) { p.addPoint(verts[i].x, verts[i].y); } p.setCenterX(center.x); p.setCenterY(center.y); p = (Polygon)p.transform(Transform.createRotateTransform(current.getAngle() + MathUtils.PI, center.x, center.y)); p = (Polygon)p.transform(Transform.createScaleTransform(pixelsPerMeter, pixelsPerMeter)); g.draw(p); break; } case CIRCLE: { f.getShape(); } default: } f = f.getNext(); } g.popTransform(); current = current.getNext(); } } public Color getColor(Body b) { Color c = new Color(1f, 1f, 1f); switch(b.m_type) { case DYNAMIC: if(b.isActive()) { c = new Color(255, 123, 0); } else { c = new Color(99, 99, 99); } break; case KINEMATIC: break; case STATIC: c = new Color(111, 111, 111); break; default: break; } return c; } } Any help with fixing the collisions would be greatly appreciated, and if you need any other code snippets I would be happy to provide them.

    Read the article

  • Which jar has JBox2d's p5 package

    - by Brantley Blanchard
    Using eclipse, I'm trying to write a simple hello world program in processing that simply draws a rectangle on the screen then has gravity drop it as seen in this Tutorial. The problem is that when I try to import the p5 package, it's not resolving so I can't declare my Physics object. I tried two things. Download the zip, unzip it, then import the 3 jars (library, serialization, & testbed) a. import org.jbox2d.p5.*; doesn't resolve but the others do b. Physics physics; doesn't resolve Download the older standalone testbed jar then import it a. Physics physics; doesn't resolve; Here is basically where I'm starting import org.jbox2d.util.nonconvex.*; import org.jbox2d.dynamics.contacts.*; import org.jbox2d.testbed.*; import org.jbox2d.collision.*; import org.jbox2d.common.*; import org.jbox2d.dynamics.joints.*; import org.jbox2d.p5.*; import org.jbox2d.dynamics.*; import processing.core.PApplet; public class MyFirstJBox2d extends PApplet { Physics physics; public void setup() { size(640,480); frameRate(60); initScene(); } public void draw() { background(0); if (keyPressed) { //Reset everything physics.destroy(); initScene(); } } public void initScene() { physics = new Physics(this, width, height); physics.setDensity(1.0f); physics.createRect(300,200,340,300); } }

    Read the article

  • OutOfBounds Exception when creating a PolygonShape using jbox2d

    - by B3nGr33ni3r
    So here's the deal, i'm parsing a file that contains the vertices for a polygon, that i want to create in box2d. I create a new PolygonShape() and then call .set() giving it a defined array of Vec, and that defined array's .length property. I expected this to work, since the documentation for jbox2d says this method takes a Vec array, and the count of Vec objects in that array. However, it errors out, and it seems to be unrelated to my code. The error i get is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8 at org.jbox2d.collision.shapes.PolygonShape.set(PolygonShape.java:174) and, upon looking at that line in the jbox2d svn repository, i still cannot figure out the issue. Any help is appreciated!

    Read the article

  • Using texture() in combination with JBox2D

    - by Valentino Ru
    I'm getting some trouble using the texture() method inside beginShape()/endShape() clause. In the display()-method of my class TowerElement (a bar which is DYNAMIC), I draw the object like following: void display(){ Vec2 pos = level.getLevel().getBodyPixelCoord(body); float a = body.getAngle(); // needed for rotation pushMatrix(); translate(pos.x, pos.y); rotate(-a); fill(temp); // temp is a color defined in the constructor stroke(0); beginShape(); vertex(-w/2,-h/2); vertex(w/2,-h/2); vertex(w/2,h-h/2); vertex(-w/2,h-h/2); endShape(CLOSE); popMatrix(); } Now, according to the API, I can use the texture() method inside the shape definition. Now when I remove the fill(temp) and put texture(img) (img is a PImage defined in the constructor), the stroke gets drawn, but the bar isn't filled and I get the warning texture() is not available with this renderer What can I do in order to use textures anyway? I don't even understand the error message, since I do not know much about different renderers.

    Read the article

  • Why does creating dynamic bodies in JBox2D freeze my app?

    - by Amplify91
    My game hangs/freezes when I create dynamic bullet objects with Box2D and I don't know why. I am making a game where the main character can shoot bullets by the user tapping on the screen. Each touch event spawns a new FireProjectileEvent that is handled properly by an event queue. So I know my problem is not trying to create a new body while the box2d world is locked. My bullets are then created and managed by an object pool class like this: public Projectile getProjectile(){ for(int i=0;i<mProjectiles.size();i++){ if(!mProjectiles.get(i).isActive){ return mProjectiles.get(i); } } return mSpriteFactory.createProjectile(); } mSpriteFactory.createProjectile() leads to the physics component of the Projectile class creating its box2d body. I have narrowed the issue down to this method and it looks like this: public void create(World world, float x, float y, Vec2 vertices[], boolean dynamic){ BodyDef bodyDef = new BodyDef(); if(dynamic){ bodyDef.type = BodyType.DYNAMIC; }else{ bodyDef.type = BodyType.STATIC; } bodyDef.position.set(x, y); mBody = world.createBody(bodyDef); PolygonShape dynamicBox = new PolygonShape(); dynamicBox.set(vertices, vertices.length); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.0f; mBody.createFixture(fixtureDef); mBody.setFixedRotation(true); } If the dynamic parameter is set to true my game freezes before crashing, but if it is false, it will create a projectile exactly how I want it just doesn't function properly (because a projectile is not a static object). Why does my program fail when I try to create a dynamic object at runtime but not when I create a static one? I have other dynamic objects (like my main character) that work fine. Any help would be greatly appreciated. This is a screenshot of a method profile I did: Especially notable is number 8. I'm just still unsure what I'm doing wrong. Other notes: I am using JBox2D 2.1.2.2. (Upgraded from 2.1.2.1 to try to fix this problem) When the application freezes, if I hit the back button, it appears to move my game backwards by one update tick. Very strange.

    Read the article

  • 2D Polygon Triangulation

    - by BleedObsidian
    I am creating a game engine using the JBox2D physics engine. It only allows you to create polygon fixtures up to 8 vertices, To create a body with more than 8 vertices, you need to create multiple fixtures for the body. My question is, How can I split the polygons a user creates into smaller polygons for JBox2D? Also, what topology should I use when splitting the polygons and why? (If JBox2D can have up to 8 vertices, why not split polygons into 8 per polygon)

    Read the article

  • How would I use JBox2d in Java?

    - by BluFire
    So I did some research and a found Box2d. I then proceeded to download it and the testbed. Now that i have it, I don't know how to properly use it. I'm looking for a clear simple answer on how to use the engine. The things I did was that I put it into a lib folder and referenced the JBox2D jar file. After that i got stuck. How can i use this to program games for android? I'm very confused since Box2d was intended for C++.

    Read the article

  • JBox2D applyLinearImpulse doesn't work

    - by Romeo
    So i have this line of code: if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), cam.screenToWorld(body.getPosition())); System.out.println("I can jump!"); } My problem is that the console display I can jump! but the body doesn't do that. Can you explain to me if i do something wrong? Some more code. This function creates my 'hero' the one supposed to jump. private Body setDynamic(float width, float height, float x, float y) { PolygonShape shape = new PolygonShape(); shape.setAsBox(width/2, height/2); BodyDef bd = new BodyDef(); bd.allowSleep = true; bd.position = new Vec2(cam.screenToWorld(new Vec2(x + width / 2, y + height / 2))); bd.type = BodyType.DYNAMIC; bd.userData = new BodyInfo(width, height); Body body = world.createBody(bd); body.createFixture(shape, 10); return body; } And this is the main update loop: if(input.isKeyDown(Input.KEY_A)) { body.setLinearVelocity(new Vec2(-10*delta, body.getLinearVelocity().y)); } else if (input.isKeyDown(Input.KEY_D)) { body.setLinearVelocity(new Vec2(10*delta, body.getLinearVelocity().y)); } else { body.setLinearVelocity(new Vec2(0, body.getLinearVelocity().y)); } if(input.isKeyDown(Input.KEY_W)&&canJump()) { body.applyLinearImpulse(new Vec2(0, 30), body.getPosition()); System.out.println("I can jump!"); } world.step(delta * 0.001f, 10, 5); }

    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

  • What is the most performant 2D graphics engine for use with Android?

    - by nbolton
    I have managed to make a hello world JBox2D application, and it works (I have some bouncing balls). However, I just read a comment on a forum post, which claims that JBox2D produces a lot of garbage, and so causes animation to be poor. Is this true? If yes, then what other 2D engines are available to me? I would very much like to use a physics engine for my 2D game, even if it's just a very simple one.

    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

  • Box2D random crash when adding joints

    - by user46624
    I'm currently working on a project which uses Box2D, when the player uses a certain key it should anchor to the ground. For that I use a weld joint, but when I add the joint the game will sometimes crash, it has a 1/10 change to crash. The error I recieve: Showing the controller Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 at org.jbox2d.dynamics.Island.add(Island.java:577) at org.jbox2d.dynamics.World.solve(World.java:1073) at org.jbox2d.dynamics.World.step(World.java:598) The code for adding the joints: WeldJointDef def = new WeldJointDef(); def.initialize(body, anchoredObject.body, body.getWorldCenter()); weldJoint = (WeldJoint) world.createJoint(def); I still get the error if I synchronize it

    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 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

  • 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

  • Transforms in Box2D

    - by user1264811
    I'm attempting to implement a camera in my game. I had it working for regular objects, but I began using Box2D and obviously things changed a bit. I have a Body object that I want to draw at the center of the screen. Basically what I'm doing is subtracting the viewportX and viewportY to the Body. I use this code that currently is not working as it should: public void paint(Graphics2D g, int viewportX, int viewportY) { Transform xf = new Transform(); // m_body is the Body object xf.set(m_body.getTransform()); // Here what I attemp to do is take the transform and alter it // by the viewportX and Y, which is something like **-240, -150**. // Why is it negative? Because an object has coordinates 500, 300 would be displayed // at 160, 150 when the subtraction is done. // With the DrawUtils.toScale(), it's just how I convert the units from JBox2D units // to my units. Vec2 v = Transform.mulTrans(xf, new Vec2(DrawUtils.toScale(-viewportX), DrawUtils.toScale(-viewportY))); // Set the new transform to the new vector. Keep the old angle. xf.set(v, xf.q.getAngle()); g.setColor(Color.white); // I know for a fact that the following method works 100%. It correctly displays // my object, just that it doesn't follow it. for (Fixture f = m_body.getFixtureList(); f != null; f = f.getNext()) DrawUtils.drawShape(f, xf); } Hopefully I didn't over comment this and you understand my problem. I don't want to alter the actual physics position of the object, I just want to display it in the center.

    Read the article

1