Java Code Examples for com.badlogic.gdx.physics.box2d.Fixture#getBody()

The following examples show how to use com.badlogic.gdx.physics.box2d.Fixture#getBody() . 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: 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 2
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 3
Source File: InputManagerGDX.java    From Entitas-Java with MIT License 5 votes vote down vote up
private void testPoint(Fixture fixture, PointerState<Vector2,Vector3> pointerState) {
    if (!fixture.testPoint(pointerState.coordinates.x, pointerState.coordinates.y))
        return;
    Integer index = (Integer) fixture.getBody().getUserData();
    GameEntity entity =  Indexed.getInteractiveEntity(index);
    if(entity.isDraggable()) {
        jointDef.bodyB = fixture.getBody();
        jointDef.target.set(pointerState.coordinates.x, pointerState.coordinates.y);
        joints[pointerState.pointer] = (MouseJoint) physics.createJoint(jointDef);
    }
}
 
Example 4
Source File: GameLevelController.java    From tilt-game-android with MIT License 5 votes vote down vote up
private boolean checkContact(Contact contact) {
    // ignore not touching contacts
    if (!contact.isTouching()) return false;

    Fixture fixtureA = contact.getFixtureA();
    if (fixtureA == null) return false;

    Fixture fixtureB = contact.getFixtureB();
    if (fixtureB == null) return false;

    Body bodyA = fixtureA.getBody();
    Body bodyB = fixtureB.getBody();

    String nameA = (String) bodyA.getUserData();
    String nameB = (String) bodyB.getUserData();

    if (nameA == null || nameB == null) {               // nameless bodies, check if sound needs to be played
        checkCollisionSound(contact, bodyA, bodyB);
        return false;
    } else if (nameA.equals(ObjectName.EDGE_SENSOR_NAME) || nameB.equals(ObjectName.EDGE_SENSOR_NAME)) {    // check edges
        Log.d(TAG, "onUpdate: OFF THE EDGE");

        setBallOut();

        return true;
    } else if (nameA.equals(ObjectName.SINKHOLE_NAME) || nameB.equals(ObjectName.SINKHOLE_NAME)) {  // check sinkhole
        Log.d(TAG, "onUpdate: SINKHOLE");

        setLevelComplete();

        return true;
    }

    return false;
}
 
Example 5
Source File: DragAndDropSample.java    From Codelabs with MIT License 5 votes vote down vote up
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
	/*
	 * Define a new QueryCallback. This callback will be used in
	 * world.QueryAABB method.
	 */
	QueryCallback queryCallback = new QueryCallback() {

		@Override
		public boolean reportFixture(Fixture fixture) {
			boolean testResult;

			/*
			 * If the hit point is inside the fixture of the body, create a
			 * new MouseJoint.
			 */
			if (testResult = fixture.testPoint(touchPosition.x,
					touchPosition.y)) {
				mouseJointDef.bodyB = fixture.getBody();
				mouseJointDef.target.set(touchPosition.x, touchPosition.y);
				mouseJoint = (MouseJoint) world.createJoint(mouseJointDef);
			}

			return testResult;
		}
	};

	/* Translate camera point to world point */
	camera.unproject(touchPosition.set(screenX, screenY, 0));

	/*
	 * Query the world for all fixtures that potentially overlap the touched
	 * point.
	 */
	world.QueryAABB(queryCallback, touchPosition.x, touchPosition.y,
			touchPosition.x, touchPosition.y);

	return true;
}
 
Example 6
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 7
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 8
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 9
Source File: CarImpactManager.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
private void ifCarThenCollide (Contact contact, Fixture f, Fixture other, ContactImpulse impulse) {
	Body body = f.getBody();
	Object userData = f.getUserData();
	if ((body != null) && (userData == CarType.PlayerCar || userData == CarType.ReplayCar)) {
		Car car = (Car)body.getUserData();
		float[] impulses = impulse.getNormalImpulses();
		tmpVec2.set(impulses[0], impulses[1]);

		// dbg
		Fixture fcar = null;
		if (contact.getFixtureA().getUserData() == CarType.PlayerCar) {
			fcar = contact.getFixtureA();
		} else if (contact.getFixtureB().getUserData() == CarType.PlayerCar) {
			fcar = contact.getFixtureB();
		}

		// assumes perfect side collision
		float front_ratio = 0.5f;

		// compute median front/rear ratio for collision points
		if (fcar != null) {
			front_ratio = 0;
			float ml = car.getCarModel().length;
			float half_ml = ml * 0.5f;
			Vector2[] pts = contact.getWorldManifold().getPoints();

			int num_points = contact.getWorldManifold().getNumberOfContactPoints();
			for (int i = 0; i < num_points; i++) {
				Vector2 lp = fcar.getBody().getLocalPoint(pts[i]);

				// examine front/rear ratio
				float r = MathUtils.clamp(lp.y + half_ml, 0, ml);
				r /= ml;
				front_ratio += r;
			}

			front_ratio /= (float)num_points;
			// Gdx.app.log("Cntct", "" + front_ratio);
		}
		// dbg

		car.onCollide(other, tmpVec2, front_ratio);
	}
}
 
Example 10
Source File: NearSensorSystem.java    From Entitas-Java with MIT License 4 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();
        Body bodyB = colliderB.getBody();

        for (Fixture fixture : bodyB.getFixtureList()) {
            if(fixture.isSensor()) return;
        }

        if (indexEntityA != null && indexEntityB != null && tagSensorA != null) {
            GameEntity entityA = Indexed.getInteractiveEntity(indexEntityA);
            GameEntity entityB = Indexed.getInteractiveEntity(indexEntityB);
            if (entityA != null && entityB != null && tagSensorA != null) {
                for (SensorEntity entity : sensorGroup.getEntities()) {
                    if (entity.getLink().ownerEntity == indexEntityA) {
                        NearSensor sensor = entity.getNearSensor();
                        if (sensor.targetTag != null && entityB.getTags().values.contains(sensor.targetTag)) {
                            if (collisionSignal) {
                                if (tagSensorA.equals("NearSensor")) {
                                    sensor.distanceContactList.add(indexEntityB);
                                    if (entity.getLink().sensorReference.contains("RadialGravity")) {
                                        bodyB.setGravityScale(0);
                                        bodyB.resetMassData();
                                    }

                                } else if (tagSensorA.equals("ResetNearSensor")) {
                                    sensor.resetDistanceContactList.add(indexEntityB);
                                }

                            } else {
                                if (tagSensorA.equals("NearSensor")) {
                                    sensor.distanceContactList.remove(indexEntityB);
                                    if (entity.getLink().sensorReference.contains("RadialGravity")) {
                                        bodyB.setGravityScale(1);
                                        bodyB.resetMassData();
                                    }
                                } else if (tagSensorA.equals("ResetNearSensor")) {
                                    sensor.resetDistanceContactList.remove(indexEntityB);
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}
 
Example 11
Source File: BuoyancyController.java    From Codelabs with MIT License 4 votes vote down vote up
private void applyForces(Fixture fixture, Vector2[] clippedPolygon) {
	PolygonProperties polygonProperties = PolygonIntersector
			.computePolygonProperties(clippedPolygon);

	/* Get fixtures bodies */
	Body fixtureBody = fixture.getBody();
	Body fluidBody = fluidSensor.getBody();

	/* Get fluid density */
	float density = fluidSensor.getDensity();

	/* Apply buoyancy force */
	float displacedMass = fluidSensor.getDensity()
			* polygonProperties.getArea();
	Vector2 gravity = world.getGravity();
	Vector2 buoyancyForce = new Vector2(-gravity.x * displacedMass,
			-gravity.y * displacedMass);
	fixtureBody.applyForce(buoyancyForce, polygonProperties.getCentroid(),
			true);

	/* Linear drag force */
	if (linearDrag != 0) {
		fixtureBody.applyForce(gravity.rotate90(1).nor().scl(linearDrag),
				polygonProperties.getCentroid(), true);
	}

	/* Apply drag and lift forces */
	int polygonVertices = clippedPolygon.length;
	for (int i = 0; i < polygonVertices; i++) {

		/* Apply drag force */

		/* End points and mid point of the edge */
		Vector2 firstPoint = clippedPolygon[i];
		Vector2 secondPoint = clippedPolygon[(i + 1) % polygonVertices];
		Vector2 midPoint = firstPoint.cpy().add(secondPoint).scl(0.5f);

		/*
		 * Find relative velocity between the object and the fluid at edge
		 * mid point.
		 */
		Vector2 velocityDirection = new Vector2(fixtureBody
				.getLinearVelocityFromWorldPoint(midPoint)
				.sub(fluidBody.getLinearVelocityFromWorldPoint(midPoint)));
		float velocity = velocityDirection.len();
		velocityDirection.nor();

		Vector2 edge = secondPoint.cpy().sub(firstPoint);
		float edgeLength = edge.len();
		edge.nor();

		Vector2 normal = new Vector2(edge.y, -edge.x);
		float dragDot = normal.dot(velocityDirection);

		if (dragDot >= 0) {

			/*
			 * Normal don't point backwards. This is a leading edge. Store
			 * the result of multiply edgeLength, density and velocity
			 * squared
			 */
			float tempProduct = edgeLength * density * velocity * velocity;

			float drag = dragDot * fluidDrag * tempProduct;
			drag = Math.min(drag, maxFluidDrag);
			Vector2 dragForce = velocityDirection.cpy().scl(-drag);
			fixtureBody.applyForce(dragForce, midPoint, true);

			/* Apply lift force */
			float liftDot = edge.dot(velocityDirection);
			float lift = dragDot * liftDot * fluidLift * tempProduct;
			lift = Math.min(lift, maxFluidLift);
			Vector2 liftDirection = new Vector2(-velocityDirection.y,
					velocityDirection.x);
			Vector2 liftForce = liftDirection.scl(lift);
			fixtureBody.applyForce(liftForce, midPoint, true);
		}
	}
}
 
Example 12
Source File: FluidSimulatorGeneric.java    From fluid-simulator-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean reportFixture (Fixture fixture) {
	logicHitBody = fixture.getBody();
	return false;
}