/** * create Revolute Joint */ public RevoluteJoint createRevoluteJoint(Body bodyA, Body bodyB, Vector2 jointPositionA, Vector2 jointPositionB, boolean enabledMotor, int maxMotorTorque, int motorSpeed) { RevoluteJointDef rJoint = new RevoluteJointDef(); rJoint.bodyA = bodyA; rJoint.bodyB = bodyB; rJoint.localAnchorA.set(jointPositionA.x * WORLD_TO_BOX, jointPositionA.y * WORLD_TO_BOX); rJoint.localAnchorB.set(jointPositionB.x * WORLD_TO_BOX, jointPositionB.y * WORLD_TO_BOX); rJoint.enableMotor = enabledMotor; rJoint.maxMotorTorque = maxMotorTorque; rJoint.motorSpeed = motorSpeed; RevoluteJoint joint = (RevoluteJoint) world.createJoint(rJoint); return joint; }
private void createBody() { BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; // Set our body's starting position in the world bodyDef.position.set(Gdx.input.getX() / 100f, camera.viewportHeight - Gdx.input.getY() / 100f); // Create our body in the world using our body definition Body body = world.createBody(bodyDef); // Create a circle shape and set its radius to 6 PolygonShape square = new PolygonShape(); square.setAsBox(0.3f, 0.3f); // Create a fixture definition to apply our shape to FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = square; fixtureDef.density = 0.5f; fixtureDef.friction = 0.5f; fixtureDef.restitution = 0.5f; // Create our fixture and attach it to the body body.createFixture(fixtureDef); square.dispose(); }
@Override public void handleCollision(Ball ball, Body bodyHit, Field field) { if (retractWhenHit) { this.setRetracted(true); } if (killBall) { field.removeBall(ball); } else { Vector2 impulse = this.impulseForBall(ball); if (impulse!=null) { ball.applyLinearImpulse(impulse); flashForFrames(3); } } }
/** Creates a circle object with the given position and radius. Resitution defaults to 0.6. */ public static Body createCircle(World world, float x, float y, float radius, boolean isStatic) { CircleShape sd = new CircleShape(); sd.setRadius(radius); FixtureDef fdef = new FixtureDef(); fdef.shape = sd; fdef.density = 1.0f; fdef.friction = 0.3f; fdef.restitution = 0.6f; BodyDef bd = new BodyDef(); bd.allowSleep = true; bd.position.set(x, y); Body body = world.createBody(bd); body.createFixture(fdef); if (isStatic) { body.setType(BodyDef.BodyType.StaticBody); } else { body.setType(BodyDef.BodyType.DynamicBody); } return body; }
/** * Creates a wall by constructing a rectangle whose corners are (xmin,ymin) and (xmax,ymax), * and rotating the box counterclockwise through the given angle, with specified restitution. */ public static Body createWall(World world, float xmin, float ymin, float xmax, float ymax, float angle, float restitution) { float cx = (xmin + xmax) / 2; float cy = (ymin + ymax) / 2; float hx = Math.abs((xmax - xmin) / 2); float hy = Math.abs((ymax - ymin) / 2); PolygonShape wallshape = new PolygonShape(); // Don't set the angle here; instead call setTransform on the body below. This allows future // calls to setTransform to adjust the rotation as expected. wallshape.setAsBox(hx, hy, new Vector2(0f, 0f), 0f); FixtureDef fdef = new FixtureDef(); fdef.shape = wallshape; fdef.density = 1.0f; if (restitution>0) fdef.restitution = restitution; BodyDef bd = new BodyDef(); bd.position.set(cx, cy); Body wall = world.createBody(bd); wall.createFixture(fdef); wall.setType(BodyDef.BodyType.StaticBody); wall.setTransform(cx, cy, angle); return wall; }
/** * Erzeugt automatisch einen Kreis als statischen Trigger. * * @see AttackHandler#createAttackFixture(Body, Shape) * * @param position der Mittelpunkt des Kreises * @param radius der Radius des Kreises */ public void createStaticAttackBody(Vector2 position, float radius) { CircleShape circle = new CircleShape(); circle.setPosition(new Vector2(position.x, position.y).scl(Physics.MPP)); circle.setRadius(radius * Physics.MPP); BodyDef triggerDef = new BodyDef(); triggerDef.type = BodyDef.BodyType.StaticBody; Body trigger = manager.getPhysicalWorld().createBody(triggerDef); createAttackFixture(trigger, circle); circle.dispose(); }
@Override public void processCollision(Field field, FieldElement element, Body hitBody, Ball ball) { // When center red bumper is hit, start multiball if all center rollovers are lit, // otherwise retract left barrier. String elementID = element.getElementId(); if ("CenterBumper1".equals(elementID)) { WallElement barrier = (WallElement)field.getFieldElementById("LeftTubeBarrier"); RolloverGroupElement multiballRollovers = (RolloverGroupElement)field.getFieldElementById("ExtraBallRollovers"); if (multiballRollovers.allRolloversActive()) { barrier.setRetracted(false); startMultiball(field); multiballRollovers.setAllRolloversActivated(false); } else { // don't retract during multiball if (field.getBalls().size()==1) { barrier.setRetracted(true); } } } }
@Override public void processCollision(Field field, FieldElement element, Body hitBody, Ball ball) { // Add bumper bonus if active. if (element instanceof BumperElement) { double extraEnergy = 0; if (bumperBonusActive) { double fractionRemaining = 1 - (((double) bumperBonusNanosElapsed) / bumperBonusDurationNanos); extraEnergy = fractionRemaining * bumperBonusMultiplier; // Round score to nearest multiple of 10. double bonusScore = element.getScore() * extraEnergy; field.addScore(10 * (Math.round(bonusScore / 10))); } bumperEnergy = Math.min(bumperEnergy + 1 + extraEnergy, maxBumperEnergy); double ratio = (bumperEnergy) / maxBumperEnergy; field.getFieldElementById("BumperIndicator").setNewColor(colorForTemperatureRatio(ratio)); checkForEnableMultiball(field); } }
/** * Creates a pivoted platform from the given object, at the given world. * * @param world The world were the platform will be. * @param object The object used to initialize the platform. * @return The Platform Model of the created platform. */ static PlatformModel makePlatform(World world, RectangleMapObject object) { PlatformModel platform = new PlatformModel(world, object); Boolean pivoted = object.getProperties().get("pivoted", boolean.class); if (pivoted != null && pivoted == true) { Rectangle rect = object.getRectangle(); RectangleMapObject anchorRect = new RectangleMapObject( rect.getX() + rect.getWidth() / 2, rect.getY() + rect.getHeight() / 2, 1, 1 ); Body anchor = makeRectGround(world, anchorRect); RevoluteJointDef jointDef = new RevoluteJointDef(); jointDef.initialize(anchor, platform.getBody(), platform.getBody().getWorldCenter()); world.createJoint(jointDef); } return platform; }
/** * Creates polygon ground from the given object, at the given world. * * @param world The world were the ground will be. * @param object The object used to initialize the ground. * @return The body of the created ground. */ static Body makePolygonGround(World world, PolygonMapObject object) { Polygon polygon = object.getPolygon(); // Body and Fixture variables BodyDef bdef = new BodyDef(); FixtureDef fdef = new FixtureDef(); PolygonShape shape = new PolygonShape(); bdef.type = BodyDef.BodyType.StaticBody; bdef.position.set(PIXEL_TO_METER * polygon.getX(), PIXEL_TO_METER * polygon.getY()); Body body = world.createBody(bdef); float[] new_vertices = polygon.getVertices().clone(); for (int i = 0; i < new_vertices.length; i++) new_vertices[i] *= PIXEL_TO_METER; shape.set(new_vertices); fdef.shape = shape; fdef.filter.categoryBits = GROUND_BIT; body.createFixture(fdef); return body; }
/** * Creates rectangular ground from the given object, at the given world. * * @param world The world were the ground will be. * @param object The object used to initialize the ground. * @return The body of the created ground. */ static Body makeRectGround(World world, RectangleMapObject object) { Rectangle rect = object.getRectangle(); // Body and Fixture variables BodyDef bdef = new BodyDef(); FixtureDef fdef = new FixtureDef(); PolygonShape shape = new PolygonShape(); bdef.type = BodyDef.BodyType.StaticBody; bdef.position.set(PIXEL_TO_METER * (rect.getX() + rect.getWidth() / 2), PIXEL_TO_METER * (rect.getY() + rect.getHeight() / 2)); Body body = world.createBody(bdef); shape.setAsBox((rect.getWidth() / 2) * PIXEL_TO_METER, (rect.getHeight() / 2) * PIXEL_TO_METER); fdef.shape = shape; fdef.filter.categoryBits = GROUND_BIT; body.createFixture(fdef); return body; }
/** * Logic associated to the Ball. * Controls the Ball's current state, making it jump if on the ground, making it dunk if flying. */ public void jump() { Body body = getBody(); switch (this.state) { case LANDED: body.applyLinearImpulse(new Vector2(0, jump_force), body.getWorldCenter(), true); this.state = State.FLYING; break; case FLYING: body.applyLinearImpulse(new Vector2(0, -1.5f * jump_force), body.getWorldCenter(), true); this.state = State.DUNKING; break; case DUNKING: // Do nothing break; default: System.err.println("Unhandled state in BallEntity"); } }
/** * Create static body from a TiledObject Refer the box2d manual to * understand the static body * * @param o * TiledObject */ public Body createStaticCircleBody(float x, float y, float radius) { BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyType.StaticBody; // transform into box2d x = x * WORLD_TO_BOX; // get position-y of object from map y = Gdx.graphics.getHeight() - y; // transform into box2d y = y * WORLD_TO_BOX; groundBodyDef.position.set(x, y); Body groundBody = world.createBody(groundBodyDef); CircleShape shape = new CircleShape(); ((CircleShape) shape).setRadius(radius * WORLD_TO_BOX / 2); groundBody.createFixture(shape, 0.0f); groundBody.setUserData("static"); return groundBody; }
/** * Erzeugt automatisch aus einem MapObject einen statischen Trigger. * * @see AttackHandler#createAttackFixture(Body, Shape) * * @param mapObject das MapObject */ public void createStaticAttackBody(MapObject mapObject) { Shape shape = PhysicsTileMapBuilder.createShape(mapObject, PhysicsTileMapBuilder.TYPE_TRIGGER); if (shape == null) { Gdx.app.log("WARNING", "Unkown trigger type! The attack object " + mapObject.getName() + " will be ignored!"); return; } BodyDef triggerDef = new BodyDef(); triggerDef.type = BodyDef.BodyType.StaticBody; Body trigger = manager.getPhysicalWorld().createBody(triggerDef); createAttackFixture(trigger, shape); shape.dispose(); }
/** * Apply a force to physics object with a force apply position * * @param data * @param force * @param applyPoint */ protected void applyForce(IPhysicsObject data, Vector2 force, Vector2 applyPoint) { Iterator<Body> bi = world.getBodies(); while (bi.hasNext()) { Body b = bi.next(); IPhysicsObject e; try { e = (IPhysicsObject) b.getUserData(); // get the IPhysicsObject } catch (Exception ex) { e = null; } if (e != null) { if (e == data) { if (applyPoint == null) b.applyForceToCenter(force); else b.applyForce(force, applyPoint); } } } }
public Body createTempBody(float x, float y, FixtureDef fixtureDef) { // Dynamic Body BodyDef bodyDef = new BodyDef(); if (box2dDebug) bodyDef.type = BodyType.StaticBody; else bodyDef.type = BodyType.DynamicBody; // transform into box2d x = x * WORLD_TO_BOX; y = y * WORLD_TO_BOX; bodyDef.position.set(x, y); Body body = world.createBody(bodyDef); Shape shape = new CircleShape(); ((CircleShape) shape).setRadius(1 * WORLD_TO_BOX); if (fixtureDef == null) throw new GdxRuntimeException("fixtureDef cannot be null!"); fixtureDef.shape = shape; body.createFixture(fixtureDef); return body; }
public Body createTempBodyDistanceJoint(Body bodyA, Body bodyB, Vector2 localA, Vector2 localB, int length) { DistanceJointDef dJoint = new DistanceJointDef(); FixtureDef fixtureDef = createFixtureDef(1f, 0.5f, 0.2f, (short) 0x0004); IPhysicsObject sprite = (IPhysicsObject) bodyA.getUserData(); Body temp = createTempBody(sprite.getX(), sprite.getY(), fixtureDef); createRevoluteJoint(bodyA, temp, localA, Vector2.Zero); dJoint.bodyA = temp; dJoint.bodyB = bodyB; dJoint.localAnchorA.set(localA.x * WORLD_TO_BOX, localA.y * WORLD_TO_BOX); dJoint.localAnchorB.set(localB.x * WORLD_TO_BOX, localB.y * WORLD_TO_BOX); dJoint.length = length * WORLD_TO_BOX; world.createJoint(dJoint); return temp; }
private void createRope(Body bodyA, Vector2 anchorA, Body bodyB, Vector2 anchorB, float sag, AtlasRegion ropeRegion) { RopeJointDef jd = new RopeJointDef(); jd.bodyA = bodyA; jd.bodyB = bodyB; jd.localAnchorA.set(anchorA.x, anchorA.y); jd.localAnchorB.set(anchorB.x, anchorB.y); // Max length of joint = current distance between bodies * sag float ropeLength = bodyA.getWorldPoint(anchorA).sub(bodyB.getWorldPoint(anchorB)).len() * sag; jd.maxLength = ropeLength; // Create joint RopeJoint joint = (RopeJoint)world.createJoint(jd); GdxRopeJoint ropeJoint = new GdxRopeJoint(joint, jd.localAnchorA, jd.localAnchorB); VRope newRope = new VRope(ropeJoint, this, ropeRegion); ropes.add(newRope); }
private Body createRopeTipBody() { BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; bodyDef.linearDamping = 0.5f; Body body = world.createBody(bodyDef); FixtureDef circleDef = new FixtureDef(); CircleShape circle = new CircleShape(); circle.setRadius(1.0f/PTM_RATIO); circleDef.shape = circle; circleDef.density = 10.0f; // Since these tips don't have to collide with anything // set the mask bits to zero circleDef.filter.maskBits = 0x01; //0; body.createFixture(circleDef); return body; }
public void cutTheRobe(Vector2 pt0, Vector2 pt1) { for (VRope rope : ropes) { for (VStick stick : rope.vSticks) { Vector2 pa = stick.getPointA().point(); Vector2 pb = stick.getPointB().point(); if (checkLineIntersection(pt0, pt1, pa, pb)) { Body newBodyA = createRopeTipBody(); Body newBodyB = createRopeTipBody(); VRope newRope = rope.cutRopeInStick(stick, newBodyA, newBodyB); ropes.add(newRope); return; } } } }
/** * Create static body from a TiledObject Refer the box2d manual to * understand the static body * * @param o * TiledObject */ public Body createStaticBoxBody(float x, float y, float width, float height) { BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyType.StaticBody; // transform into box2d x = x * WORLD_TO_BOX; // get position-y from map y = tileMapRenderer.getMapHeightUnits() - y; // transform into box2d y = y * WORLD_TO_BOX; groundBodyDef.position.set(x, y); Body groundBody = world.createBody(groundBodyDef); PolygonShape polygon = new PolygonShape(); ((PolygonShape) polygon).setAsBox(width * WORLD_TO_BOX / 2, height * WORLD_TO_BOX / 2); groundBody.createFixture(polygon, 0.0f); groundBody.setUserData("static"); return groundBody; }
/** * Create static body from a TiledObject Refer the box2d manual to * understand the static body * * @param o * TiledObject */ public Body createStaticCircleBody(float x, float y, float radius) { BodyDef groundBodyDef = new BodyDef(); groundBodyDef.type = BodyType.StaticBody; // transform into box2d x = x * WORLD_TO_BOX; // get position-y of object from map y = tileMapRenderer.getMapHeightUnits() - y; // transform into box2d y = y * WORLD_TO_BOX; groundBodyDef.position.set(x, y); Body groundBody = world.createBody(groundBodyDef); CircleShape shape = new CircleShape(); ((CircleShape) shape).setRadius(radius * WORLD_TO_BOX / 2); groundBody.createFixture(shape, 0.0f); groundBody.setUserData("static"); return groundBody; }
public static Array<Body> createTopTube(World world, float posX) { float posY = generateTubePosition(); BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.KinematicBody; bodyDef.position.set(posX, posY); PolygonShape shape = new PolygonShape(); shape.setAsBox(Constants.TUBE_WIDTH / 2, Constants.TUBE_HEIGHT / 2); Body bodyTop = world.createBody(bodyDef); bodyTop.createFixture(shape, 0f); bodyTop.resetMassData(); shape.dispose(); bodyTop.setLinearVelocity(Constants.TUBE_SPEED, 0.0f); Array<Body> bodies = new Array<Body>(); bodies.add(bodyTop); bodies.add(createBottomTube(world, posX, posY)); return bodies; }
/** * Erlaubt es den Unterklassen möglichst einfach einen beliebigen Box2D Körper zu erstellen. * * @param position die Startposition des Body * @param shape die Form, die für dne Body verwendet werden soll * @param type der Typ des Körpers * @return ein Box2D Körper */ protected Body createEntityBody(Vector2 position, Shape shape, BodyDef.BodyType type) { position.scl(Physics.MPP); BodyDef bodyDef = new BodyDef(); bodyDef.type = type; bodyDef.position.set(position); bodyDef.fixedRotation = true; Body body = worldObjectManager.getPhysicalWorld().createBody(bodyDef); body.setUserData(this); FixtureDef fixture = new FixtureDef(); fixture.shape = shape; fixture.filter.categoryBits = Physics.CATEGORY_ENTITIES; fixture.filter.maskBits = Physics.MASK_ENTITIES; body.createFixture(fixture).setUserData(this); shape.dispose(); return body; }
/** * Erzeugt aus einer Form ein Fixture und fügt dieses einem Körper hinzu. * Das Fixture wird als Trigger für Angriffe benutzt. * * @param body der Körper * @param shape die Form */ public void createAttackFixture(Body body, Shape shape) { FixtureDef fixture = new FixtureDef(); fixture.shape = shape; fixture.isSensor = true; fixture.filter.categoryBits = Physics.CATEGORY_TRIGGER; fixture.filter.maskBits = Physics.MASK_TRIGGER; body.createFixture(fixture).setUserData(this); }
@Override public boolean onTouchUp(TouchEvent e) { if (status != Status.touched) { return true; } // If mouse is up when dragging the bird // fire the bird float distanceX = getCenterX() - sling.getCenterX(); float distanceY = getCenterY() - sling.getCenterY(); // Here we have velocityX and velocityY of bird float velocityX = distanceX * -1 / 5; float velocityY = distanceY * -1 / 5; Vector2 birdVelocity = new Vector2(velocityX, velocityY); // get PhysicManager from gameService PhysicsManager physicsManager = getGameService().getService( PhysicsManager.class); // create new physicObject in physicsManager Body birdBody = physicsManager.addDynamicCircleObject(this, getRegionWidth() / 2, 4f, 0.8f, 0.5f); // Set above velocity for the bird body birdBody.setLinearVelocity(birdVelocity); // set bullet, it will make game run preciously birdBody.setBullet(true); // update the bird's status status = Status.released; return false; }
/** Creates a segment-like thin wall with 0.05 thickness going from (x1,y1) to (x2,y2) */ public static Body createThinWall(World world, float x1, float y1, float x2, float y2, float restitution) { // Determine center point and rotation angle for createWall. float cx = (x1 + x2) / 2; float cy = (y1 + y2) / 2; float angle = (float)Math.atan2(y2-y1, x2-x1); float mag = (float)Math.hypot(y2-y1, x2-x1); return createWall(world, cx - mag/2, cy-0.05f, cx + mag/2, cy+0.05f, angle, restitution); }
@Override public void createBodies(World world) { for (float[] parray : positions) { float restitution = 0f; Body wallBody = Box2DFactory.createThinWall( world, parray[0], parray[1], parray[2], parray[3], restitution); allBodies.add(wallBody); } }
public RevoluteJoint createRevoluteJoint(Body bodyA, Body bodyB, Vector2 jointPositionA, Vector2 jointPositionB) { RevoluteJointDef rJoint = new RevoluteJointDef(); rJoint.bodyA = bodyA; rJoint.bodyB = bodyB; rJoint.localAnchorA.set(jointPositionA.x * WORLD_TO_BOX, jointPositionA.y * WORLD_TO_BOX); rJoint.localAnchorB.set(jointPositionB.x * WORLD_TO_BOX, jointPositionB.y * WORLD_TO_BOX); RevoluteJoint joint = (RevoluteJoint) world.createJoint(rJoint); return joint; }
public static Body createSky(World world) { BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.StaticBody; bodyDef.position.set(0, Constants.HEIGHT); Body body = world.createBody(bodyDef); PolygonShape shape = new PolygonShape(); shape.setAsBox(Constants.GROUND_SIZE.x, 0); body.createFixture(shape, 0f); shape.dispose(); return body; }
@Override public void draw(IFieldRenderer renderer) { // draw line for each target Color color = currentColor(DEFAULT_COLOR); int bsize = allBodies.size(); for(int i=0; i<bsize; i++) { Body body = allBodies.get(i); if (body.isActive()) { float[] parray = positions[i]; renderer.drawLine(parray[0], parray[1], parray[2], parray[3], color); } } }
private Ball ballWithBody(Body body) { for (int i=0; i<this.balls.size(); i++) { Ball ball = this.balls.get(i); if (ball.getBody() == body) { return ball; } } return null; }
/** * Create mouse joint with default ground body, target body and location on target body * @param targetBody * @param locationWorld * @return */ public MouseJoint createMouseJoint(Body targetBody, Vector2 locationWorld){ BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyType.DynamicBody; bodyDef.position.set(new Vector2(locationWorld.x * WORLD_TO_BOX, locationWorld.y * WORLD_TO_BOX)); bodyDef.linearDamping = 0.3f; Body body = world.createBody(bodyDef); return createMouseJoint(body, targetBody, locationWorld); }
public void applyRotation(Field field, double dt) { currentAngle += dt*rotationSpeed; if (currentAngle>TAU) currentAngle -= TAU; if (currentAngle<0) currentAngle += TAU; for(int i=0; i<elementIDs.length; i++) { double angle = currentAngle + angleIncrement*i; FieldElement element = field.getFieldElementById(elementIDs[i]); Body body = element.getBodies().get(0); double x = centerX + radius*Math.cos(angle); double y = centerY + radius*Math.sin(angle); body.setTransform((float)x, (float)y, body.getAngle()); } }
public Tube(Array<Body> bodies) { random = new Random(); topTubeTexture = AssetsManager.getTextureRegion(Constants.TOP_TUBE_NAME); bottomTubeTexture = AssetsManager.getTextureRegion(Constants.BOTTOM_TUBE_NAME); topTubeBody = bodies.first();//first item bottomTubeBody = bodies.peek();//last item }
public Body createBody(Vector2 position, Texture texture, BodyDef.BodyType bodyType, World world, Shape.Type shape, Vector3 densityRestitutionFriction) { this.texture = texture; bodyDef = createBodyDef(bodyType, position); body = world.createBody(bodyDef); FixtureCreator.createFixture(body, createShape(shape), densityRestitutionFriction); return body; }
public B2dSteeringEntity(Body body, float boundingRadius) { this.body = body; this.boundingRadius = boundingRadius; this.maxAngularSpeed = 500; this.maxLinearAcceleration = 5000; this.maxAngularSpeed = 30; this.maxAngularAcceleration = 5; this.tagged = false; this.steeringOutput = new SteeringAcceleration<Vector2>(new Vector2()); this.body.setUserData(this); }
/** * Erlaubt es den Unterklassen möglichst einfach einen runden Box2D Körper zu erstellen. * * @param position die Startposition des Body * @param radius der Radius der Form * @return ein Box2D Körper */ protected Body createCircleBody(Vector2 position, float radius) { CircleShape circle = new CircleShape(); circle.setPosition(Vector2.Zero); circle.setRadius(radius * Physics.MPP); return createEntityBody(position, circle); }