com.badlogic.gdx.physics.box2d.Body Java Examples

The following examples show how to use com.badlogic.gdx.physics.box2d.Body. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Box2dSteeringTest.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
protected void renderBox (ShapeRenderer shapeRenderer, Body body, float halfWidth, float halfHeight) {
	// get the bodies center and angle in world coordinates
	Vector2 pos = body.getWorldCenter();
	float angle = body.getAngle();

	// set the translation and rotation matrix
	transform.setToTranslation(Box2dSteeringTest.metersToPixels(pos.x), Box2dSteeringTest.metersToPixels(pos.y), 0);
	transform.rotate(0, 0, 1, angle * MathUtils.radiansToDegrees);

	// render the box
	shapeRenderer.begin(ShapeType.Line);
	shapeRenderer.setTransformMatrix(transform);
	shapeRenderer.setColor(1, 1, 1, 1);
	shapeRenderer.rect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);
	shapeRenderer.end();
}
 
Example #2
Source File: DebugRenderer.java    From tilt-game-android with MIT License 6 votes vote down vote up
/**
 * Translates b2d Fixture to appropriate color, depending on body state/type
 * Modify to suit your needs
 * @param fixture
 * @return
 */
private static Color fixtureToColor(Fixture fixture) {
	if (fixture.isSensor()) {
		return Color.PINK;
	} else {
		Body body = fixture.getBody();
		if (!body.isActive()) {
			return Color.BLACK;
		} else {
			if (!body.isAwake()) {
				return Color.RED;
			} else {
				switch (body.getType()) {
				case StaticBody:
					return Color.CYAN;
				case KinematicBody:
					return Color.WHITE;
				case DynamicBody:
				default:
					return Color.GREEN;
				}
			}
		}
	}
}
 
Example #3
Source File: PulleyJointDef.java    From tilt-game-android with MIT License 6 votes vote down vote up
/**
 * Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
 */
public void initialize (Body bodyA, Body bodyB, Vector2 groundAnchorA, Vector2 groundAnchorB, Vector2 anchorA,
	Vector2 anchorB, float ratio) {
	this.bodyA = bodyA;
	this.bodyB = bodyB;
	this.groundAnchorA.set(groundAnchorA);
	this.groundAnchorB.set(groundAnchorB);
	this.localAnchorA.set(bodyA.getLocalPoint(anchorA));
	this.localAnchorB.set(bodyB.getLocalPoint(anchorB));
	lengthA = anchorA.dst(groundAnchorA);
	lengthB = anchorB.dst(groundAnchorB);
	this.ratio = ratio;
	float C = lengthA + ratio * lengthB;
	maxLengthA = C - ratio * minPulleyLength;
	maxLengthB = (C - minPulleyLength) / ratio;

}
 
Example #4
Source File: Box2DFactory.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
/** 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;
}
 
Example #5
Source File: Scene2dRaycastObstacleAvoidanceTest.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
private void renderBox (ShapeRenderer shapeRenderer, Body body, float halfWidth, float halfHeight) {
	// get the bodies center and angle in world coordinates
	Vector2 pos = body.getWorldCenter();
	float angle = body.getAngle();

	// set the translation and rotation matrix
	transform.setToTranslation(pos.x, pos.y, 0);
	transform.rotate(0, 0, 1, (float)Math.toDegrees(angle));

	// render the box
	shapeRenderer.begin(ShapeType.Line);
	shapeRenderer.setTransformMatrix(transform);
	shapeRenderer.setColor(1, 1, 1, 1);
	shapeRenderer.rect(-halfWidth, -halfHeight, halfWidth * 2, halfHeight * 2);
	shapeRenderer.end();
}
 
Example #6
Source File: PhysicsConnector.java    From tilt-game-android with MIT License 6 votes vote down vote up
@Override
public void onUpdate(final float pSecondsElapsed) {
	final IEntity entity = this.mEntity;
	final Body body = this.mBody;

	if (this.mUpdatePosition) {
		final Vector2 position = body.getPosition();
		final float pixelToMeterRatio = this.mPixelToMeterRatio;
		entity.setPosition(position.x * pixelToMeterRatio, position.y * pixelToMeterRatio);
	}

	if (this.mUpdateRotation) {
		final float angle = body.getAngle();
		entity.setRotation(-MathUtils.radToDeg(angle));
	}
}
 
Example #7
Source File: Box2dSteeringTest.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
public Box2dSteeringEntity createSteeringEntity (World world, TextureRegion region, boolean independentFacing, int posX, int posY) {

		CircleShape circleChape = new CircleShape();
		circleChape.setPosition(new Vector2());
		int radiusInPixels = (int)((region.getRegionWidth() + region.getRegionHeight()) / 4f);
		circleChape.setRadius(Box2dSteeringTest.pixelsToMeters(radiusInPixels));

		BodyDef characterBodyDef = new BodyDef();
		characterBodyDef.position.set(Box2dSteeringTest.pixelsToMeters(posX), Box2dSteeringTest.pixelsToMeters(posY));
		characterBodyDef.type = BodyType.DynamicBody;
		Body characterBody = world.createBody(characterBodyDef);

		FixtureDef charFixtureDef = new FixtureDef();
		charFixtureDef.density = 1;
		charFixtureDef.shape = circleChape;
		charFixtureDef.filter.groupIndex = 0;
		characterBody.createFixture(charFixtureDef);

		circleChape.dispose();

		return new Box2dSteeringEntity(region, characterBody, independentFacing, Box2dSteeringTest.pixelsToMeters(radiusInPixels));
	}
 
Example #8
Source File: Field4Delegate.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
@Override public void processCollision(Field field, FieldElement element, Body hitBody, Ball ball) {
    String id = element.getElementId();
    if (id!=null && id.startsWith("Bumper.")) {
        String suffix = id.substring(7);
        // Increment multiplier.
        long multiplier = Math.round(field.getScoreMultiplier()*100);
        multiplier += bumperMultiplierIncrease;
        field.setScoreMultiplier(multiplier / 100.0);
        // Unlock next multiball target if all bumpers hit.
        if (ballsLocked < 3) {
            RolloverGroupElement statusRollovers = multiballStatusRollovers.get(suffix);
            statusRollovers.setRolloverActiveAtIndex(ballsLocked, true);
            if (allStatusRolloversActiveForIndex(ballsLocked)) {
                // If rollover for ball lock isn't already active, activate and show message.
                RolloverGroupElement lockedBallRollover = lockedBallRollovers.get(ballsLocked);
                if (lockedBallRollover.getIgnoreBall()) {
                    lockedBallRollover.setIgnoreBall(false);
                    lockedBallRollover.setVisible(true);
                    lockedBallRollover.setRolloverActiveAtIndex(0, false);
                    String msg = (ballsLocked == 2) ? "Multiball Ready" : "Ball Lock Ready";
                    field.showGameMessage(msg, 3000);
                }
            }
        }
    }
}
 
Example #9
Source File: DebugHelper.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
private void renderPlayerInfo (SpriteBatch batch, int y) {
	if (!hasPlayer) return;

	CarDescriptor carDesc = player.getCarDescriptor();
	Body body = player.getBody();
	Vector2 pos = GameRenderer.ScreenUtils.worldMtToScreen(body.getPosition());
	EntityRenderState state = player.state();

	SpriteBatchUtils.drawString(batch, "vel_wc len =" + carDesc.velocity_wc.len(), 0, y);
	SpriteBatchUtils.drawString(batch, "vel_wc [x=" + carDesc.velocity_wc.x + ", y=" + carDesc.velocity_wc.y + "]", 0, y
		+ Art.DebugFontWidth);
	SpriteBatchUtils.drawString(batch, "steerangle=" + carDesc.steerangle, 0, y + Art.DebugFontWidth * 2);
	SpriteBatchUtils.drawString(batch, "throttle=" + carDesc.throttle, 0, y + Art.DebugFontWidth * 3);
	SpriteBatchUtils.drawString(batch, "screen x=" + pos.x + ",y=" + pos.y, 0, y + Art.DebugFontWidth * 4);
	SpriteBatchUtils.drawString(batch, "world-mt x=" + body.getPosition().x + ",y=" + body.getPosition().y, 0, y
		+ Art.DebugFontWidth * 5);
	SpriteBatchUtils.drawString(batch,
		"world-px x=" + Convert.mt2px(body.getPosition().x) + ",y=" + Convert.mt2px(body.getPosition().y), 0, y
			+ Art.DebugFontWidth * 6);
	SpriteBatchUtils.drawString(batch, "orient=" + body.getAngle(), 0, y + Art.DebugFontWidth * 7);
	SpriteBatchUtils.drawString(batch, "render.interp=" + (state.position.x + "," + state.position.y), 0, y
		+ Art.DebugFontWidth * 8);

	// BatchUtils.drawString( batch, "on tile " + tilePosition, 0, 0 );
}
 
Example #10
Source File: Field3Delegate.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #11
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 5 votes vote down vote up
/**
 * @param pPhysicsWorld
 * @param pEntity
 * @param pTriangleVertices are to be defined relative to the center of the pEntity and have the {@link PhysicsConstants#PIXEL_TO_METER_RATIO_DEFAULT} applied.
 * 					The vertices will be triangulated and for each triangle a {@link Fixture} will be created.
 * @param pBodyType
 * @param pFixtureDef
 * @return
 */
public static Body createTrianglulatedBody(final PhysicsWorld pPhysicsWorld, final IEntity pEntity, final List<Vector2> pTriangleVertices, final BodyType pBodyType, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final Vector2[] TMP_TRIANGLE = new Vector2[3];

	final BodyDef boxBodyDef = new BodyDef();
	boxBodyDef.type = pBodyType;

	final float[] sceneCenterCoordinates = pEntity.getSceneCenterCoordinates();
	boxBodyDef.position.x = sceneCenterCoordinates[Constants.VERTEX_INDEX_X] / pPixelToMeterRatio;
	boxBodyDef.position.y = sceneCenterCoordinates[Constants.VERTEX_INDEX_Y] / pPixelToMeterRatio;

	final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);

	final int vertexCount = pTriangleVertices.size();
	for (int i = 0; i < vertexCount; /* */) {
		final PolygonShape boxPoly = new PolygonShape();

		TMP_TRIANGLE[2] = pTriangleVertices.get(i++);
		TMP_TRIANGLE[1] = pTriangleVertices.get(i++);
		TMP_TRIANGLE[0] = pTriangleVertices.get(i++);

		boxPoly.set(TMP_TRIANGLE);
		pFixtureDef.shape = boxPoly;

		boxBody.createFixture(pFixtureDef);

		boxPoly.dispose();
	}

	return boxBody;
}
 
Example #12
Source File: RaySensorSystemTest.java    From Entitas-Java with MIT License 5 votes vote down vote up
public RaySensorSystemTest() {
    collections = new EntitasCollections(new CollectionsFactories() {});
    entitas = new Entitas();
    world = new World();
    Body body = Mockito.mock(Body.class);
    when(body.getPosition()).thenReturn(new Vector2());

    this.raySensorSystem = new RaySensorSystem(entitas, world);
    Indexed.initialize(entitas);

    boss = entitas.game.createEntity()
            .addTags("Enemy", "Boss")
            .addRigidBody(body)
            .setInteractive(true);

    groundEntity = entitas.game.createEntity()
            .addTags("Ground", "Ground")
            .addRigidBody(body)
            .setInteractive(true);

    playerEntity = entitas.game.createEntity()
            .addTags("Player", "Player1")
            .addRigidBody(body)
            .setInteractive(true);

    sensorEntity = entitas.sensor.createEntity()
            .addRaySensor("Boss", Axis2D.Xnegative, 1, false)
            .addLink(playerEntity.getCreationIndex(),"");

    sensorEntity2 = entitas.sensor.createEntity()
            .addRaySensor("Ground", Axis2D.Xnegative, 1, false)
            .addLink(playerEntity.getCreationIndex(),"");

    sensorEntity4 = entitas.sensor.createEntity()
            .addRaySensor("Ground", Axis2D.Xnegative, 1, false)
            .addLink(boss.getCreationIndex(),"");

}
 
Example #13
Source File: WeldJointDef.java    From tilt-game-android with MIT License 5 votes vote down vote up
public void initialize (Body body1, Body body2, Vector2 anchor) {
	this.bodyA = body1;
	this.bodyB = body2;
	this.localAnchorA.set(body1.getLocalPoint(anchor));
	this.localAnchorB.set(body2.getLocalPoint(anchor));
	referenceAngle = body2.getAngle() - body1.getAngle();
}
 
Example #14
Source File: EnemySystem.java    From Bomberman_libGdx with MIT License 5 votes vote down vote up
protected boolean hitSomethingVertical(final Body body, Vector2 fromV, Vector2 toV) {
    World b2dWorld = body.getWorld();
    hit = false;

    RayCastCallback rayCastCallback = new RayCastCallback() {

        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            // if hit the player, ignore it
            if (fixture.getFilterData().categoryBits == GameManager.PLAYER_BIT || fixture.getFilterData().categoryBits == GameManager.POWERUP_BIT) {
                return 0;
            }

            if (fraction < 1.0f) {
                hit = true;
            }
            return 0;
        }
    };

    for (int i = 0; i < 3; i++) {
        Vector2 tmpV = new Vector2(toV);
        b2dWorld.rayCast(rayCastCallback, fromV, tmpV.add((1 - i) * 0.4f, 0));

    }
    return hit;
}
 
Example #15
Source File: NinjaRabbitBodyFactory.java    From ninja-rabbit with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Body create(final World world, final BodyDef definition, final Direction direction) {
	Body rabbitBody = world.createBody(definition);
	loader.attachFixture(rabbitBody, RABBIT_IDENTIFIER + "-" + direction.direction(), fdef, NINJA_RABBIT_SCALE);

	Fixture footSensor = rabbitBody.getFixtureList().get(FOOT_FIXTURE_INDEX);
	footSensor.setUserData(NinjaRabbitPhysicsProcessor.FOOT_IDENTIFIER);
	footSensor.setDensity(0.0f);
	footSensor.setSensor(true);

	rabbitBody.resetMassData();

	return rabbitBody;
}
 
Example #16
Source File: PhysicsConnector.java    From tilt-game-android with MIT License 5 votes vote down vote up
public PhysicsConnector(final IEntity pEntity, final Body pBody, final boolean pUdatePosition, final boolean pUpdateRotation, final float pPixelToMeterRatio) {
	this.mEntity = pEntity;
	this.mBody = pBody;

	this.mUpdatePosition = pUdatePosition;
	this.mUpdateRotation = pUpdateRotation;
	this.mPixelToMeterRatio = pPixelToMeterRatio;
}
 
Example #17
Source File: PlayerComponent.java    From Pacman_libGdx with MIT License 5 votes vote down vote up
public PlayerComponent(Body body) {
    this.body = body;
    ai = new PlayerAI(body);
    playerAgent = new PlayerAgent(this);
    playerAgent.stateMachine.setInitialState(PlayerState.IDLE_RIGHT);
    currentState = IDLE_RIGHT;
    hp = 1;
    invincibleTimer = 0;
}
 
Example #18
Source File: WorldUtils.java    From martianrun with Apache License 2.0 5 votes vote down vote up
public static Body createRunner(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(new Vector2(Constants.RUNNER_X, Constants.RUNNER_Y));
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(Constants.RUNNER_WIDTH / 2, Constants.RUNNER_HEIGHT / 2);
    Body body = world.createBody(bodyDef);
    body.setGravityScale(Constants.RUNNER_GRAVITY_SCALE);
    body.createFixture(shape, Constants.RUNNER_DENSITY);
    body.resetMassData();
    body.setUserData(new RunnerUserData(Constants.RUNNER_WIDTH, Constants.RUNNER_HEIGHT));
    shape.dispose();
    return body;
}
 
Example #19
Source File: Mariano.java    From Entitas-Java with MIT License 5 votes vote down vote up
@Override
public GameEntity create(Engine engine, Context<GameEntity> context) {

    BasePhysicsManager physics = engine.getManager(BasePhysicsManager.class);
    BodyBuilder bodyBuilder =  physics.getBodyBuilder();

    TextureAtlas textureAtlas = assetsManager.getTextureAtlas(atlas);

    Array<TextureAtlas.AtlasRegion> heroWalking = textureAtlas.findRegions("Andando");
    Array<TextureAtlas.AtlasRegion> heroJump = textureAtlas.findRegions("Saltando");
    Array<TextureAtlas.AtlasRegion> heroFall = textureAtlas.findRegions("Cayendo");
    Array<TextureAtlas.AtlasRegion> heroIdle = textureAtlas.findRegions("Parado");

    Map<String, Animation<TextureRegion>> animationStates = Collections.createMap(String.class, Animation.class);
    animationStates.put("walking", new Animation(0.02f, heroWalking, Animation.PlayMode.LOOP));
    animationStates.put("jump", new Animation(0.02f * 7, heroJump, Animation.PlayMode.NORMAL));
    animationStates.put("fall", new Animation(0.02f * 5, heroFall, Animation.PlayMode.NORMAL));
    animationStates.put("idle", new Animation(0.02f * 4, heroIdle, Animation.PlayMode.LOOP));

    Body bodyPlayer = bodyBuilder.fixture(bodyBuilder.fixtureDefBuilder()
            .boxShape(0.35f, 1)
            .density(1))
            .type(BodyDef.BodyType.DynamicBody)
            .fixedRotation()
            .position(0, 5)
            .mass(1)
            .build();



    GameEntity entity = ((GameContext) context).getPlayerEntity()
            .addRigidBody(bodyPlayer)
            .addAnimations(animationStates, animationStates.get("idle"), 0)
            .addCharacter("Mariano", StateCharacter.IDLE, false)
            .addMovable(7,8)
            .addTextureView(null, new Bounds(0.9f,1.15f),false, false,1,1, Color.WHITE);


    return entity;
}
 
Example #20
Source File: PhysicsFactory.java    From tilt-game-android with MIT License 5 votes vote down vote up
public static Body createLineBody(final PhysicsWorld pPhysicsWorld, final Line pLine, final FixtureDef pFixtureDef, final float pPixelToMeterRatio) {
	final float[] sceneCoordinates = pLine.convertLocalCoordinatesToSceneCoordinates(0, 0);
	final float x1 = sceneCoordinates[Constants.VERTEX_INDEX_X];
	final float y1 = sceneCoordinates[Constants.VERTEX_INDEX_Y];

	pLine.convertLocalCoordinatesToSceneCoordinates(pLine.getX2() - pLine.getX1(), pLine.getY2() - pLine.getY1());
	final float x2 = sceneCoordinates[Constants.VERTEX_INDEX_X];
	final float y2 = sceneCoordinates[Constants.VERTEX_INDEX_Y];

	return PhysicsFactory.createLineBody(pPhysicsWorld, x1, y1, x2, y2, pFixtureDef, pPixelToMeterRatio);
}
 
Example #21
Source File: Box2DFactory.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
/** 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);
}
 
Example #22
Source File: LineJointDef.java    From tilt-game-android with MIT License 5 votes vote down vote up
/**
 * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis.
 */
public void initialize (Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis) {
	this.bodyA = bodyA;
	this.bodyB = bodyB;
	localAnchorA.set(bodyA.getLocalPoint(anchor));
	localAnchorB.set(bodyB.getLocalPoint(anchor));
	localAxisA.set(bodyA.getLocalVector(axis));
}
 
Example #23
Source File: DropTargetGroupElement.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example #24
Source File: PhysicsConnectorManager.java    From tilt-game-android with MIT License 5 votes vote down vote up
public Body findBodyByShape(final IEntity pShape) {
	final ArrayList<PhysicsConnector> physicsConnectors = this;
	for (int i = physicsConnectors.size() - 1; i >= 0; i--) {
		final PhysicsConnector physicsConnector = physicsConnectors.get(i);
		if (physicsConnector.mEntity == pShape) {
			return physicsConnector.mBody;
		}
	}
	return null;
}
 
Example #25
Source File: PlayerSystem.java    From Pacman_libGdx with MIT License 5 votes vote down vote up
@Override
protected void processEntity(Entity entity, float deltaTime) {
    PlayerComponent player = playerM.get(entity);
    StateComponent state = stateM.get(entity);
    MovementComponent movement = movementM.get(entity);
    Body body = movement.body;

    if (player.hp > 0) {
        if ((Gdx.input.isKeyPressed(Input.Keys.D) || Gdx.input.isKeyPressed(Input.Keys.RIGHT)) && checkMovable(body, MoveDir.RIGHT)) {
            body.applyLinearImpulse(tmpV1.set(movement.speed, 0).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.A) || Gdx.input.isKeyPressed(Input.Keys.LEFT)) && checkMovable(body, MoveDir.LEFT)) {
            body.applyLinearImpulse(tmpV1.set(-movement.speed, 0).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.W) || Gdx.input.isKeyPressed(Input.Keys.UP)) && checkMovable(body, MoveDir.UP)) {
            body.applyLinearImpulse(tmpV1.set(0, movement.speed).scl(body.getMass()), body.getWorldCenter(), true);

        } else if ((Gdx.input.isKeyPressed(Input.Keys.S) || Gdx.input.isKeyPressed(Input.Keys.DOWN))&& checkMovable(body, MoveDir.DOWN)) {
            body.applyLinearImpulse(tmpV1.set(0, -movement.speed).scl(body.getMass()), body.getWorldCenter(), true);

        }

        if (body.getLinearVelocity().len2() > movement.speed * movement.speed) {
            body.setLinearVelocity(body.getLinearVelocity().scl(movement.speed / body.getLinearVelocity().len()));
        }
    }

    // player is invincible for 3 seconds when spawning
    if (GameManager.instance.playerIsInvincible) {
        player.invincibleTimer += deltaTime;
        if (player.invincibleTimer >= 3.0f) {
            GameManager.instance.playerIsInvincible = false;
            player.invincibleTimer = 0;
        }
    }

    player.playerAgent.update(deltaTime);
    state.setState(player.currentState);
}
 
Example #26
Source File: Field.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #27
Source File: Box2DFactory.java    From Codelabs with MIT License 5 votes vote down vote up
public static Body createBody(World world, BodyType bodyType,
		FixtureDef fixtureDef, Vector2 position) {
	BodyDef bodyDef = new BodyDef();
	bodyDef.type = bodyType;
	bodyDef.position.set(position);

	Body body = world.createBody(bodyDef);
	body.createFixture(fixtureDef);

	fixtureDef.shape.dispose();

	return body;
}
 
Example #28
Source File: Field2Delegate.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
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());
    }
}
 
Example #29
Source File: NinjaRabbitBodyProcessor.java    From ninja-rabbit with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets a new body onto the {@link NinjaRabbit} instance, after destroying the current one. Sets
 * the current direction to the given {@link Direction}.
 *
 * @param character
 *            The {@link NinjaRabbit} being updated.
 * @param direction
 *            The direction the {@link NinjaRabbit} is facing.
 */
private void changeDirection(final Entity character) {
	Vector2 position = character.getBody().getPosition();
	Vector2 velocity = character.getBody().getLinearVelocity();
	float angle = character.getBody().getAngle();

	world.destroyBody(character.getBody());
	Body newBody = bodyFactory.create(world, character.getDirection());
	newBody.setTransform(position, angle);
	newBody.setLinearVelocity(velocity);
	character.setBody(newBody);
	newBody.setUserData(character);

	lastKnownDirection = character.getDirection();
}
 
Example #30
Source File: Field5Delegate.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
@Override public void processCollision(Field field, FieldElement element, Body bodyHit, Ball ball) {
    if (multiballStatus == MultiballStatus.READY) {
        if (triangleWalls.contains(element)) {
            ((WallElement)element).setRetracted(true);
        }
    }
}