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

The following examples show how to use com.badlogic.gdx.physics.box2d.Fixture. 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: Field.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Called after Box2D world step method, to notify FieldElements that the ball collided with.
 */
void processBallContacts() {
    for(int i=0; i<contactedBalls.size(); i++) {
        Ball ball = contactedBalls.get(i);
        Fixture f = contactedFixtures.get(i);
        FieldElement element = bodyToFieldElement.get(f.getBody());
        if (element!=null) {
            element.handleCollision(ball, f.getBody(), this);
            if (delegate!=null) {
                delegate.processCollision(this, element, f.getBody(), ball);
            }
            if (element.getScore()!=0) {
                this.gameState.addScore(element.getScore());
                audioPlayer.playScore();
            }
        }
    }
}
 
Example #2
Source File: RenderOfPolyFixture.java    From tilt-game-android with MIT License 6 votes vote down vote up
public RenderOfPolyFixture(Fixture fixture, VertexBufferObjectManager pVBO) {
	super(fixture);

	PolygonShape fixtureShape = (PolygonShape) fixture.getShape();
	int vSize = fixtureShape.getVertexCount();
	float[] xPoints = new float[vSize];
	float[] yPoints = new float[vSize];

	Vector2 vertex = Vector2Pool.obtain();
	for (int i = 0; i < fixtureShape.getVertexCount(); i++) {
		fixtureShape.getVertex(i, vertex);
		xPoints[i] = vertex.x * PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT;
		yPoints[i] = vertex.y * PhysicsConnector.PIXEL_TO_METER_RATIO_DEFAULT;
	}
	Vector2Pool.recycle(vertex);

	mEntity = new PolyLine(0, 0, xPoints, yPoints, pVBO);
}
 
Example #3
Source File: Light.java    From box2dlights with Apache License 2.0 6 votes vote down vote up
@Override
final public float reportRayFixture(Fixture fixture, Vector2 point,
		Vector2 normal, float fraction) {
	
	if ((globalFilterA != null) && !globalContactFilter(fixture))
		return -1;
	
	if ((filterA != null) && !contactFilter(fixture))
		return -1;
	
	if (ignoreBody && fixture.getBody() == getBody())
		return -1;
	
	// if (fixture.isSensor())
	// return -1;
	
	mx[m_index] = point.x;
	my[m_index] = point.y;
	f[m_index] = fraction;
	return fraction;
}
 
Example #4
Source File: RaySensorSystem.java    From Entitas-Java with MIT License 6 votes vote down vote up
float reportRayFixture (RaySensor sensor, Fixture fixture){
    Integer indexEntity = (Integer) fixture.getBody().getUserData();
    sensor.collisionSignal = false;
    GameEntity entity = Indexed.getInteractiveEntity(indexEntity);

    if (sensor.targetTag != null && entity.getTags().values.contains(sensor.targetTag)) {
        sensor.rayContactList.add(indexEntity);
        sensor.collisionSignal = true;
    } else if (sensor.targetTag == null ) {
        sensor.rayContactList.add(indexEntity);
        sensor.collisionSignal = true;
    }

    if (sensor.xRayMode) return 1;
    else return 0;
}
 
Example #5
Source File: CollisionSensorSystem.java    From Entitas-Java with MIT License 6 votes vote down vote up
@Override
public void processCollision(Fixture colliderA, Fixture colliderB, boolean collisionSignal) {
    Integer indexEntityA = (Integer) colliderA.getBody().getUserData();
    Integer indexEntityB = (Integer) colliderB.getBody().getUserData();
    if (indexEntityA != null && indexEntityB != null) {
        GameEntity entityA =  Indexed.getInteractiveEntity(indexEntityA);
        GameEntity entityB =  Indexed.getInteractiveEntity(indexEntityB);
        if (entityA != null && entityB != null) {
            for (SensorEntity entity : sensorGroup.getEntities()) {
                CollisionSensor collision = entity.getCollisionSensor();
                if (entityB.getTags().values.contains(collision.targetTag)) {
                    if (collisionSignal) {
                        Indexed.addEntityInSensor(entity, entityB);
                    } else {
                        Indexed.removeEntityInSensor(entity, entityB);
                    }
                    collision.collisionSignal = collisionSignal;
                }
            }
        }
    }
}
 
Example #6
Source File: RadarSensorSystem.java    From Entitas-Java with MIT License 6 votes vote down vote up
@Override
public void processCollision(Fixture colliderA, Fixture colliderB, boolean collisionSignal) {
    if (colliderA.isSensor() && !colliderB.isSensor()) {
        Integer indexEntityA = (Integer) colliderA.getBody().getUserData();
        Integer indexEntityB = (Integer) colliderB.getBody().getUserData();
        String tagSensorA = (String) colliderA.getUserData();

        if (indexEntityA != null && indexEntityB != null && tagSensorA != null && tagSensorA.equals("RadarSensor")) {
            GameEntity entityB = Indexed.getInteractiveEntity(indexEntityB);
            if (entityB != null) {
                for (SensorEntity entity : sensorGroup.getEntities()) {
                    RadarSensor radar = entity.getRadarSensor();
                    if (entityB.getTags().values.contains(radar.targetTag)) {
                        if (collisionSignal) {
                            Indexed.addEntityInSensor(entity, entityB);
                        } else {
                            Indexed.removeEntityInSensor(entity, entityB);
                        }
                        radar.collisionSignal = collisionSignal;
                    }

                }
            }
        }
    }
}
 
Example #7
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 #8
Source File: DebugRenderer.java    From tilt-game-android with MIT License 6 votes vote down vote up
public RenderOfBody(Body pBody, VertexBufferObjectManager pVBO) {
	ArrayList<Fixture> fixtures = pBody.getFixtureList();

	/**
	 * Spawn all IRenderOfFixture for this body that are out there,
	 * and bind them to this RenderOfBody
	 */
	for (Fixture fixture : fixtures) {
		IRenderOfFixture renderOfFixture;
		if (fixture.getShape().getType() == Type.Circle) {
			renderOfFixture = new RenderOfCircleFixture(fixture, pVBO);
		} else {
			renderOfFixture = new RenderOfPolyFixture(fixture, pVBO);
		}

		updateColor();
		mRenderFixtures.add(renderOfFixture);
		this.attachChild(renderOfFixture.getEntity());
	}
}
 
Example #9
Source File: Field.java    From homescreenarcade with GNU General Public License v3.0 6 votes vote down vote up
@Override public void endContact(Contact contact) {
    Fixture fixture = null;
    Ball ball = ballWithBody(contact.getFixtureA().getBody());
    if (ball != null) {
        fixture = contact.getFixtureB();
    }
    else {
        ball = ballWithBody(contact.getFixtureB().getBody());
        if (ball != null) {
            fixture = contact.getFixtureA();
        }
    }

    if (ball != null) {
        contactedBalls.add(ball);
        contactedFixtures.add(fixture);
    }
}
 
Example #10
Source File: BuoyancyController.java    From Codelabs with MIT License 6 votes vote down vote up
public void step() {
	for (Fixture fixture : fixtures) {
		if (fixture.getBody().isAwake()) {

			/* Create clipPolygon */
			List<Vector2> clipPolygon = getFixtureVertices(fixture);

			/* Create subjectPolygon */
			List<Vector2> subjectPolygon;
			if (isFluidFixed) {
				subjectPolygon = fluidVertices;
			} else {
				subjectPolygon = getFixtureVertices(fluidSensor);
			}

			/* Get intersection polygon */
			List<Vector2> clippedPolygon = PolygonIntersector.clipPolygons(
					subjectPolygon, clipPolygon);

			if (!clippedPolygon.isEmpty()) {
				applyForces(fixture, clippedPolygon.toArray(new Vector2[0]));
			}
		}
	}
}
 
Example #11
Source File: FixtureAtlas.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
/** Creates and applies the fixtures defined in the editor. The name parameter is used to retrieve the shape from the loaded
 * binary file. Therefore, it _HAS_ to be the exact same name as the one that appeared. in the editor. <br/>
 * <br/>
 * 
 * WARNING: The body reference point is supposed to be the bottom left corner. As a result, calling "getPosition()" on the body
 * will return its bottom left corner. This is useful to draw a Sprite directly by setting its position to the body position. <br/>
 * <br/>
 * 
 * Also, saved shapes are normalized. Thus, you need to provide the desired width and height of your body for them to scale
 * according to your needs. <br/>
 * <br/>
 * 
 * Moreover, you can submit a custom FixtureDef object. Its parameters will be applied to every fixture applied to the body by
 * this method.
 * 
 * @param body A box2d Body, previously created.
 * @param name The name of the shape you want to load.
 * @param width The desired width of the body.
 * @param height The desired height of the body.
 * @param params Custom fixture parameters to apply. */
public void createFixtures (Body body, String name, float width, float height, FixtureDef params, Vector2 offset,
	Object userData) {
	BodyModel bm = bodyMap.get(name);
	if (bm == null) {
		Gdx.app.log("FixtureAtlas", name + " does not exist in the fixture list.");
	}

	Vector2[][] polygons = bm.getPolygons(width, height, offset);
	if (polygons == null) {
		Gdx.app.log("FixtureAtlas", name + " does not declare any polygon. "
			+ "Should not happen. Is your shape file corrupted ?");
	}

	for (Vector2[] polygon : polygons) {
		shape.set(polygon);
		FixtureDef fd = params == null ? DEFAULT_FIXTURE : params;
		fd.shape = shape;
		Fixture f = body.createFixture(fd);
		f.setUserData(userData);
	}
}
 
Example #12
Source File: BombSystem.java    From Bomberman_libGdx with MIT License 6 votes vote down vote up
private boolean checkMovable(Body body, Vector2 from, Vector2 to) {
    World b2dWorld = body.getWorld();
    moveable = true;

    RayCastCallback rayCastCallback = new RayCastCallback() {
        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            if (fixture.getFilterData().categoryBits == GameManager.INDESTRUCTIIBLE_BIT
                    | fixture.getFilterData().categoryBits == GameManager.BREAKABLE_BIT
                    | fixture.getFilterData().categoryBits == GameManager.BOMB_BIT
                    | fixture.getFilterData().categoryBits == GameManager.ENEMY_BIT
                    | fixture.getFilterData().categoryBits == GameManager.PLAYER_BIT) {
                moveable = false;
                return 0;
            }
            return 0;
        }
    };

    b2dWorld.rayCast(rayCastCallback, from, to);
    return moveable;
}
 
Example #13
Source File: ActorBuilder.java    From Bomberman_libGdx with MIT License 6 votes vote down vote up
private boolean checkCanExplodeThrough(Vector2 fromV, Vector2 toV) {
    canExplodeThrough = true;
    RayCastCallback rayCastCallback = new RayCastCallback() {

        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
            if (fixture.getFilterData().categoryBits == GameManager.INDESTRUCTIIBLE_BIT) {
                canExplodeThrough = false;
                return 0;
            }

            if (fixture.getFilterData().categoryBits == GameManager.BREAKABLE_BIT) {
                canExplodeThrough = false;
                Entity e = (Entity) fixture.getBody().getUserData();
                Breakable breakable = e.getComponent(Breakable.class);
                breakable.state = Breakable.State.EXPLODING;
                return 0;
            }
            return 0;
        }
    };

    b2dWorld.rayCast(rayCastCallback, fromV, toV);
    return canExplodeThrough;
}
 
Example #14
Source File: CollisionsSample.java    From Codelabs with MIT License 5 votes vote down vote up
@Override
public void beginContact(Contact contact) {
	Fixture fixtureA = contact.getFixtureA();
	Fixture fixtureB = contact.getFixtureB();

	/*
	 * If one of the fixture contacting is an static body, and is the wall,
	 * set ballTouchedWall to true.
	 */
	if (fixtureA.getBody().getType() == BodyType.StaticBody) {
		if (fixtureA.getBody().equals(walls)) {
			ballTouchedBox = false;
			ballTouchedWall = true;
		} else {
			ballTouchedBox = true;
			ballTouchedWall = false;
		}
	} else if (fixtureB.getBody().getType() == BodyType.StaticBody) {
		if (fixtureA.getBody().equals(walls)) {
			ballTouchedBox = false;
			ballTouchedWall = true;
		} else {
			ballTouchedBox = true;
			ballTouchedWall = false;
		}
	}
}
 
Example #15
Source File: BuoyancyController.java    From Codelabs with MIT License 5 votes vote down vote up
public void addBody(Fixture fixture) {
	try {
		PolygonShape polygon = (PolygonShape) fixture.getShape();
		if (polygon.getVertexCount() > 2) {
			fixtures.add(fixture);
		}
	} catch (ClassCastException e) {
		Gdx.app.debug("BuoyancyController",
				"Fixture shape is not an instance of PolygonShape.");
	}
}
 
Example #16
Source File: BuoyancyController.java    From Codelabs with MIT License 5 votes vote down vote up
public BuoyancyController(World world, Fixture fluidSensor) {
	this.world = world;
	this.fluidSensor = fluidSensor;
	fluidVertices = getFixtureVertices(fluidSensor);

	fixtures = new HashSet<Fixture>();
}
 
Example #17
Source File: BuoyancySample.java    From Codelabs with MIT License 5 votes vote down vote up
@Override
public void endContact(Contact contact) {
	Fixture fixtureA = contact.getFixtureA();
	Fixture fixtureB = contact.getFixtureB();

	if (fixtureA.isSensor()
			&& fixtureB.getBody().getType() == BodyType.DynamicBody) {
		buoyancyController.removeBody(fixtureB);
	} else if (fixtureB.isSensor()
			&& fixtureA.getBody().getType() == BodyType.DynamicBody) {
		if (fixtureA.getBody().getWorldCenter().y > -1) {
			buoyancyController.removeBody(fixtureA);
		}
	}
}
 
Example #18
Source File: BuoyancySample.java    From Codelabs with MIT License 5 votes vote down vote up
@Override
public void beginContact(Contact contact) {
	Fixture fixtureA = contact.getFixtureA();
	Fixture fixtureB = contact.getFixtureB();

	if (fixtureA.isSensor()
			&& fixtureB.getBody().getType() == BodyType.DynamicBody) {
		buoyancyController.addBody(fixtureB);
	} else if (fixtureB.isSensor()
			&& fixtureA.getBody().getType() == BodyType.DynamicBody) {
		buoyancyController.addBody(fixtureA);
	}
}
 
Example #19
Source File: Car.java    From uracer-kotd with Apache License 2.0 5 votes vote down vote up
public void onCollide (Fixture other, Vector2 normalImpulses, float frontRatio) {
	impacts++;

	// FIXME
	// see the bug report at https://code.google.com/p/libgdx/issues/detail?id=1398
	if (triggerEvents) {
		GameEvents.playerCar.data.setCollisionData(other, normalImpulses, frontRatio);
		GameEvents.playerCar.trigger(this, CarEvent.Type.onCollision);
	}
}
 
Example #20
Source File: BuoyancyController.java    From Codelabs with MIT License 5 votes vote down vote up
private List<Vector2> getFixtureVertices(Fixture fixture) {
	PolygonShape polygon = (PolygonShape) fixture.getShape();
	int verticesCount = polygon.getVertexCount();

	List<Vector2> vertices = new ArrayList<Vector2>(verticesCount);
	for (int i = 0; i < verticesCount; i++) {
		Vector2 vertex = new Vector2();
		polygon.getVertex(i, vertex);
		vertices.add(new Vector2(fixture.getBody().getWorldPoint(vertex)));
	}

	return vertices;
}
 
Example #21
Source File: Light.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
boolean contactFilter(Fixture fixtureB) {
	Filter filterB = fixtureB.getFilterData();

	if (filterA.groupIndex != 0 &&
		filterA.groupIndex == filterB.groupIndex)
		return filterA.groupIndex > 0;

	return  (filterA.maskBits & filterB.categoryBits) != 0 &&
			(filterA.categoryBits & filterB.maskBits) != 0;
}
 
Example #22
Source File: Light.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
boolean globalContactFilter(Fixture fixtureB) {
	Filter filterB = fixtureB.getFilterData();

	if (globalFilterA.groupIndex != 0 &&
		globalFilterA.groupIndex == filterB.groupIndex)
		return globalFilterA.groupIndex > 0;

	return  (globalFilterA.maskBits & filterB.categoryBits) != 0 &&
			(globalFilterA.categoryBits & filterB.maskBits) != 0;
}
 
Example #23
Source File: Box2dLightTest.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
@Override
public boolean reportFixture(Fixture fixture) {
	if (fixture.getBody() == groundBody)
		return true;

	if (fixture.testPoint(testPoint.x, testPoint.y)) {
		hitBody = fixture.getBody();
		return false;
	} else
		return true;
}
 
Example #24
Source File: FluidSimulatorGeneric.java    From fluid-simulator-v2 with Apache License 2.0 5 votes vote down vote up
@Override
		public boolean reportFixture (Fixture fixture) {
			if (fixture.getBody().getType() != BodyType.StaticBody && !fixture.isSensor() && ((ObjectInfo)fixture.getBody().getUserData()).isPortalAllowed) {
				// Prevent portal looping
				if (!((ObjectInfo)fixture.getBody().getUserData()).hasTimePassed(300))
					return true;
				for (int i=0; i<portalIn.size(); i++) {
					if (portalIn.get(i).fixture.testPoint(fixture.getBody().getPosition().x, fixture.getBody().getPosition().y)) {
						logicHitBody = fixture.getBody();
						if (logicHitBody != null) {
							logicHitBody.setTransform(portalOut.get(i).getBody().getPosition(), 0);
							if (portalOut.get(i).normal != null) {
								// New velocity angle
								//System.out.println("vel: "+logicHitBody.getLinearVelocity().angle()+" norm: " + portalOut.get(i).normal.angle()+" angle: " + portalOut.get(i).angle);
								logicHitBody.setLinearVelocity(logicHitBody.getLinearVelocity().rotate(portalOut.get(i).angle - logicHitBody.getLinearVelocity().angle()));
								// Apply a little more linear force
								if (allowPortalTransferForce)
									logicHitBody.applyForceToCenter(portalOut.get(i).transferForce, true);
							}
							if (fixture.getBody().getUserData() != null)
								((ObjectInfo)fixture.getBody().getUserData()).updateTime();
//							handlePortalCallbackRendering(portalIn.get(i).getBody().getPosition(), portalOut.get(i).getBody().getPosition());
						}
					}
				}
			}
			return true;
		}
 
Example #25
Source File: FluidSimulatorGeneric.java    From fluid-simulator-v2 with Apache License 2.0 5 votes vote down vote up
@Override
		public boolean reportFixture (Fixture fixture) {
			if (fixture.getBody().getType() != BodyType.StaticBody && !fixture.isSensor() && ((ObjectInfo)fixture.getBody().getUserData()).isPortalAllowed) {
				// Prevent portal looping
				if (!((ObjectInfo)fixture.getBody().getUserData()).hasTimePassed(300))
					return true;
				for (int i=0; i<portalIn.size(); i++) {
					if (portalOut.get(i).fixture.testPoint(fixture.getBody().getPosition().x, fixture.getBody().getPosition().y)) {
						logicHitBody = fixture.getBody();
						if (logicHitBody != null) {
							logicHitBody.setTransform(portalIn.get(i).getBody().getPosition(), 0);
							if (portalIn.get(i).normal != null) {
								// New velocity angle
								logicHitBody.setLinearVelocity(logicHitBody.getLinearVelocity().rotate(portalIn.get(i).normal.angle() - logicHitBody.getLinearVelocity().angle()));
								// Apply a little more linear force
								if (allowPortalTransferForce)
									logicHitBody.applyForceToCenter(portalIn.get(i).transferForce, true);
							}
							if (fixture.getBody().getUserData() != null)
								((ObjectInfo)fixture.getBody().getUserData()).updateTime();
//							handlePortalCallbackRendering(portalOut.get(i).getBody().getPosition(), portalIn.get(i).getBody().getPosition());
						}
					}
				}
			}
			return true;
		}
 
Example #26
Source File: FluidSimulatorGeneric.java    From fluid-simulator-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public float reportRayFixture(Fixture fixture, com.badlogic.gdx.math.Vector2 point, com.badlogic.gdx.math.Vector2 normal, float fraction) {
	if (fixture.getBody().getUserData() != null) {
		collisionPiece = ((ObjectInfo)fixture.getBody().getUserData()).pieceInfo;
		collisionPoint.set(point);
		collisionNormal.set(normal);
	}
	return 0;
}
 
Example #27
Source File: Portal.java    From fluid-simulator-v2 with Apache License 2.0 5 votes vote down vote up
public Portal(Fixture fixture, int angle, float forceOut) {
	this.forceOut = forceOut;
	this.angle = angle;
	this.fixture = fixture;
	this.normal = new Vector2(1, 0);
	this.normal.rotate(angle);
	this.normal.nor();
	this.transferForce.set(this.normal);
	this.transferForce.scl(forceOut);
}
 
Example #28
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 #29
Source File: CarrotPhysicsProcessor.java    From ninja-rabbit with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param contact
 */
private void collectCarrot(final Fixture fixture) {
	Collectible carrot = (Collectible) fixture.getBody().getUserData();
	if (!carrot.isCollected()) {
		carrot.setCollected(true);
		MessageManager.getInstance().dispatchMessage(null, MessageType.COLLECTED.code(), carrot);
	}
}
 
Example #30
Source File: Box2dSquareAABBProximity.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
public boolean reportFixture (Fixture fixture) {
	Steerable<Vector2> steerable = getSteerable(fixture);
	if (steerable != owner && accept(steerable)) {
		if (behaviorCallback.reportNeighbor(steerable)) neighborCount++;
	}
	return true;
}