Java Code Examples for com.badlogic.gdx.physics.box2d.World#setContactListener()

The following examples show how to use com.badlogic.gdx.physics.box2d.World#setContactListener() . 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: EntityFactory.java    From ninja-rabbit with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link NinjaRabbit}, defining its graphical, audio and physical
 * properties.
 *
 * @param world
 *            The Box2D {@link World} onto which to create the {@link Body} and {@link Fixture}
 *            of the {@link Entity}.
 * @param loader
 *            A {@link BodyEditorLoader} to handle creation of the Entity body and fixtures.
 * @param assets
 *            The {@link AssetManager} from where to extract the graphical and audio resources.
 *            Those resources should be loaded in the manager before calling this method and
 *            won't be disposed.
 * @param status
 *            A reference to the global status of the player to be updated from the changes in
 *            the returned entity inner state.
 * @param observers
 *            An array of event receivers. Events will fire when the active player status
 *            changes (such as losing lives, collecting items, etc.).
 * @return A ready to use instance of a new {@link NinjaRabbit}.
 */
public static Entity createNinjaRabbit(final World world, final BodyEditorLoader loader, final AssetManager assets,
		final CurrentPlayerStatus status, final PlayerStatusObserver... observers) {
	PhysicsProcessor physics = new NinjaRabbitPhysicsProcessor();
	CONTACT_LISTENER.add(physics);
	world.setContactListener(CONTACT_LISTENER);
	GraphicsProcessor graphics = new NinjaRabbitGraphicsProcessor(assets);
	BodyProcessor bodyProcessor = new NinjaRabbitBodyProcessor(world, loader);
	AudioProcessor audio = new NinjaRabbitAudioProcessor(assets);
	PlayerStatusProcessor player = new NinjaRabbitPlayerStatusProcessor(status);
	if (observers != null) {
		for (PlayerStatusObserver o : observers) {
			player.addObserver(o);
		}
	}
	NinjaRabbit ninjaRabbit = new NinjaRabbit(player, bodyProcessor, graphics, physics, audio);

	if (Ouya.isRunningOnOuya()) {
		Controllers.clearListeners();
		Controllers.addListener(new NinjaRabbitControllerProcessor(ninjaRabbit));
	} else {
		Gdx.input.setInputProcessor(new NinjaRabbitInputProcessor(ninjaRabbit));
	}
	return ninjaRabbit;
}
 
Example 2
Source File: EntityFactory.java    From ninja-rabbit with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates and returns a new instance of {@link Environment}, settings its physical, graphical
 * and audio attributes.
 *
 * @param world
 * @param batch
 * @param renderer
 * @param assets
 * @param observers
 * @return A newly created {@link Environment}.
 */
public static Entity createEnvironment(final World world, final Batch batch, final LevelRenderer renderer, final AssetManager assets,
		final CurrentPlayerStatus status, final PlayerStatusObserver... observers) {
	PhysicsProcessor physics = new LevelPhysicsProcessor(world, renderer.getTiledMap(), renderer.getUnitScale());
	CONTACT_LISTENER.add(physics);
	world.setContactListener(CONTACT_LISTENER);
	GraphicsProcessor graphics = new LevelGraphicsProcessor(assets, batch, renderer);
	AudioProcessor audio = new LevelAudioProcessor(assets, renderer.getTiledMap().getProperties());
	PlayerStatusProcessor player = new LevelPlayerStatusProcessor(status);
	if (observers != null) {
		for (PlayerStatusObserver o : observers) {
			player.addObserver(o);
		}
	}
	return new Environment(graphics, physics, audio, player);
}
 
Example 3
Source File: FluidSimulatorGeneric.java    From fluid-simulator-v2 with Apache License 2.0 5 votes vote down vote up
public FluidSimulatorGeneric(FluidSimulatorStarter fluidSimulatorStarter) {
		this.game = fluidSimulatorStarter;
		// LibGDX single batches cannot have a size more than 5460
		batch = new SpriteBatch(IS_DESKTOP ? 5460 : ANDROID_SIZE);
		font = new BitmapFont();
		camera = new OrthographicCamera(WORLD_WIDTH, WORLD_HEIGHT);
		camera.position.set(0, (WORLD_HEIGHT / 2) - 1, 0);
		immediateRenderer = new ImmediateModeRenderer20(SIZE*6, false, true, 0);
		irt = new Renderer20(SIZE*6, false, true, 1);
		irt2 = new ImmediateModeRenderer20(SIZE*11, false, true, 1);
		shapeRenderer = new ShapeRenderer(SIZE);
		renderer = new Box2DDebugRenderer(true, true, false, true, false, false);
		
		//3D
		camera3D = new PerspectiveCamera(67, WORLD_WIDTH, WORLD_HEIGHT);
		camera3D.position.set(0, 130f, 250f);
		camera3D.lookAt(0,150f,0);
		camera3D.near = 0.1f;
		camera3D.far = 500f;
		camera3D.update();
		ModelBuilder modelBuilder = new ModelBuilder();
//        model = modelBuilder.createSphere(5f, 5f, 5f, 4, 4, GL10.GL_TRIANGLES,
//                new Material(ColorAttribute.createDiffuse(Color.GREEN)),
//                Usage.Position | Usage.Normal);
        model = modelBuilder.createBox(5f, 5f, 5f,
            new Material(ColorAttribute.createDiffuse(Color.GREEN)),
            Usage.Position | Usage.Normal);
        instance = new ModelInstance(model);
        modelBatch = new ModelBatch();
        environment = new Environment();
        environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
        environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, 0, -0.8f, -0.2f));
        camController = new Camera3DController(camera3D);
        camController.setFluidSimulator(this);
		
		world = new World(new Vector2(0, -9.8f), false);
		world.setContactListener(this);
	}
 
Example 4
Source File: GameWorld.java    From uracer-kotd with Apache License 2.0 4 votes vote down vote up
public GameWorld (String levelId, boolean nightMode) {
	float widthRatio = (float)Config.Graphics.ReferenceScreenWidth / (float)ScaleUtils.PlayWidth;
	pixelsPerMeterFactor = ((widthRatio * 256f) / 224f) * ScaleUtils.Scale;

	box2dWorld = new World(new Vector2(0, 0), false);
	box2dWorld.setContactListener(new GameWorldContactListener());

	boolean autoClearForces = false;
	boolean continuousPhysics = false;
	box2dWorld.setAutoClearForces(autoClearForces);
	box2dWorld.setContinuousPhysics(continuousPhysics); // power off TOI and make it *really* deterministic

	Gdx.app.log("GameWorld", "Box2D world created (CCD=" + continuousPhysics + ", auto clear forces=" + autoClearForces + ")");

	map = GameLevels.load(levelId);

	this.levelId = levelId;
	this.nightMode = nightMode;

	// get map properties
	mapWidth = map.getProperties().get("width", int.class);
	mapHeight = map.getProperties().get("height", int.class);
	tileWidth = map.getProperties().get("tilewidth", int.class);
	tileHeight = map.getProperties().get("tileheight", int.class);
	invTileWidth = 1f / (float)tileWidth;

	// compute world size
	worldSizeTiles = new Vector2(mapWidth, mapHeight);
	worldSizePx = new Vector2(mapWidth * tileWidth, mapHeight * tileHeight);
	worldSizeMt = new Vector2(Convert.px2mt(mapWidth * tileWidth), Convert.px2mt(mapHeight * tileHeight));

	// initialize tilemap utils
	mapUtils = new MapUtils(map, tileWidth, mapHeight, worldSizePx);

	createMeshes();
	route = createRoute();
	polys = createTrackPolygons();
	gameTrack = new GameTrack(route, polys);

	if (route == null) {
		throw new GdxRuntimeException("No route for this track");
	}

	playerStart = gameTrack.generateTrackPosition(-3);

	if (nightMode) {
		createLights();
	}
}
 
Example 5
Source File: Field.java    From homescreenarcade with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates Box2D world, reads layout definitions for the given level, and initializes the game
 * to the starting state.
 */
public void resetForLevel(Context context, int level) {
    Vector2 gravity = new Vector2(0.0f, -1.0f);
    boolean doSleep = true;
    world = new World(gravity, doSleep);
    world.setContactListener(this);

    gameState.statusMgr = LocalBroadcastManager.getInstance(context);
    Intent scoreIntent = new Intent(ArcadeCommon.ACTION_STATUS)
            .putExtra(ArcadeCommon.STATUS_RESET_SCORE, true)
            .putExtra(ArcadeCommon.STATUS_LEVEL, level)
            .putExtra(ArcadeCommon.STATUS_LIVES, gameState.totalBalls - gameState.ballNumber);
    gameState.statusMgr.sendBroadcast(scoreIntent);
    
    layout = FieldLayout.layoutForLevel(level, world);
    world.setGravity(new Vector2(0.0f, -layout.getGravity()));
    ballsAtTargets = new HashSet<Body>();

    scheduledActions = new PriorityQueue<ScheduledAction>();
    gameTime = 0;

    // Map bodies and IDs to FieldElements, and get elements on whom tick() has to be called.
    bodyToFieldElement = new HashMap<Body, FieldElement>();
    fieldElementsByID = new HashMap<String, FieldElement>();
    List<FieldElement> tickElements = new ArrayList<FieldElement>();

    for(FieldElement element : layout.getFieldElements()) {
        if (element.getElementId()!=null) {
            fieldElementsByID.put(element.getElementId(), element);
        }
        for(Body body : element.getBodies()) {
            bodyToFieldElement.put(body, element);
        }
        if (element.shouldCallTick()) {
            tickElements.add(element);
        }
    }
    fieldElementsToTick = tickElements.toArray(new FieldElement[0]);
    fieldElementsArray = layout.getFieldElements().toArray(new FieldElement[0]);

    delegate = null;
    String delegateClass = layout.getDelegateClassName();
    if (delegateClass!=null) {
        if (delegateClass.indexOf('.')==-1) {
            delegateClass = "com.homescreenarcade.pinball.fields." + delegateClass;
        }
        try {
            delegate = (Delegate)Class.forName(delegateClass).newInstance();
        }
        catch(Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    else {
        // Use no-op delegate if no class specified, so that field.getDelegate() is non-null.
        delegate = new BaseFieldDelegate();
    }
}
 
Example 6
Source File: PlayScreen.java    From Pacman_libGdx with MIT License 4 votes vote down vote up
@Override
public void show() {
    camera = new OrthographicCamera();
    viewport = new FitViewport(WIDTH, HEIGHT, camera);
    camera.translate(WIDTH / 2, HEIGHT / 2);
    camera.update();

    batch = new SpriteBatch();

    playerSystem = new PlayerSystem();
    ghostSystem = new GhostSystem();
    movementSystem = new MovementSystem();
    pillSystem = new PillSystem();
    animationSystem = new AnimationSystem();
    renderSystem = new RenderSystem(batch);
    stateSystem = new StateSystem();

    engine = new Engine();
    engine.addSystem(playerSystem);
    engine.addSystem(ghostSystem);
    engine.addSystem(pillSystem);
    engine.addSystem(movementSystem);
    engine.addSystem(stateSystem);
    engine.addSystem(animationSystem);
    engine.addSystem(renderSystem);

    // box2d
    world = new World(Vector2.Zero, true);
    world.setContactListener(new WorldContactListener());
    box2DDebugRenderer = new Box2DDebugRenderer();
    showBox2DDebuggerRenderer = false;

    // box2d light
    rayHandler = new RayHandler(world);
    rayHandler.setAmbientLight(ambientLight);

    // load map
    tiledMap = new TmxMapLoader().load("map/map.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap, 1 / 16f, batch);

    new WorldBuilder(tiledMap, engine, world, rayHandler).buildAll();

    stageViewport = new FitViewport(WIDTH * 20, HEIGHT * 20);
    stage = new Stage(stageViewport, batch);

    font = new BitmapFont(Gdx.files.internal("fonts/army_stencil.fnt"));
    Label.LabelStyle labelStyle = new Label.LabelStyle(font, Color.WHITE);

    Label scoreTextLabel = new Label("SCORE", labelStyle);
    scoreTextLabel.setPosition(WIDTH * 1, HEIGHT * 19);
    stage.addActor(scoreTextLabel);

    Label hightScoreTextLabel = new Label("High Score", labelStyle);
    hightScoreTextLabel.setPosition(WIDTH * 14, HEIGHT * 19);
    stage.addActor(hightScoreTextLabel);

    scoreLabel = new Label("0", labelStyle);
    scoreLabel.setPosition(WIDTH * 1.5f, HEIGHT * 18.2f);
    stage.addActor(scoreLabel);

    highScoreLabel = new Label("0", labelStyle);
    highScoreLabel.setPosition(WIDTH * 16.5f, HEIGHT * 18.2f);
    stage.addActor(highScoreLabel);

    gameOverLabel = new Label("              - Game Over -\n Press Enter to continue", labelStyle);
    gameOverLabel.setPosition(WIDTH * 4.3f, HEIGHT * 9f);
    gameOverLabel.setVisible(false);
    stage.addActor(gameOverLabel);

    TextureAtlas textureAtlas = GameManager.instance.assetManager.get("images/actors.pack", TextureAtlas.class);
    pacmanSprite = new Sprite(new TextureRegion(textureAtlas.findRegion("Pacman"), 16, 0, 16, 16));
    pacmanSprite.setBounds(8f, 21.5f, 16 / GameManager.PPM, 16 / GameManager.PPM);

    stringBuilder = new StringBuilder();

    changeScreen = false;
}
 
Example 7
Source File: JumpingSample.java    From Codelabs with MIT License 4 votes vote down vote up
@Override
public void show() {
	/*
	 * This line is found in every sample but is not necessary for the
	 * sample functionality. calls Sample.show() method. That method set the
	 * sample to receive all touch and key input events. Also prevents the
	 * app from be closed whenever the user press back button and instead
	 * returns to main menu.
	 */
	super.show();

	/*
	 * Create world with a common gravity vector (9.81 m/s2 downwards force)
	 * and tell world that we want objects to sleep. This last value
	 * conserves CPU usage.
	 */
	world = new World(new Vector2(0, -9.81f), true);

	/* Create renderer */
	debugRenderer = new Box2DDebugRenderer();

	/*
	 * Define camera viewport. Box2D uses meters internally so the camera
	 * must be defined also in meters. We set a desired width and adjust
	 * height to different resolutions.
	 */
	camera = new OrthographicCamera(20,
			20 * (Gdx.graphics.getHeight() / (float) Gdx.graphics
					.getWidth()));

	/*
	 * Next line must remain commented because we do this in its parent (See
	 * Sample class). In case you are not using Sample class, uncomment this
	 * line to set input processor to handle events.
	 */
	// Gdx.input.setInputProcessor(this);

	/* Create the player */
	Shape shape = Box2DFactory.createBoxShape(0.35f, 1, new Vector2(0, 0),
			0);
	FixtureDef fixtureDef = Box2DFactory.createFixture(shape, 1, 0, 0,
			false);
	player = Box2DFactory.createBody(world, BodyType.DynamicBody,
			fixtureDef, new Vector2(0, 0));

	/*
	 * Create foot sensor. This sensor will be used to detect when the
	 * player is standing on something.
	 */
	shape = Box2DFactory.createBoxShape(0.1f, 0.1f, new Vector2(0, -1), 0);
	fixtureDef = Box2DFactory.createFixture(shape, 0, 0, 0, true);

	/*
	 * Set user data to the player. In this case we are using an integer.
	 * This will help us to identify the fixture during collision handling.
	 */
	player.createFixture(fixtureDef).setUserData(new Integer(3));

	/*
	 * Fix the rotation of player's body. We don't want our player to fall
	 * every time he/she touch an object :)
	 */
	player.setFixedRotation(true);

	/* Create the walls */
	Box2DFactory.createWalls(world, camera.viewportWidth,
			camera.viewportHeight, 1);

	world.setContactListener(this);
}
 
Example 8
Source File: CollisionsSample.java    From Codelabs with MIT License 4 votes vote down vote up
@Override
public void show() {
	/*
	 * This line is found in every sample but is not necessary for the
	 * sample functionality. calls Sample.show() method. That method set the
	 * sample to receive all touch and key input events. Also prevents the
	 * app from be closed whenever the user press back button and instead
	 * returns to main menu.
	 */
	super.show();

	/*
	 * Create world with a common gravity vector (9.81 m/s2 downwards force)
	 * and tell world that we want objects to sleep. This last value
	 * conserves CPU usage. As we use the accelerometer and the world
	 * gravity to change bodies positions, we can't let bodies to sleep.
	 */
	world = new World(new Vector2(0, -9.81f), false);

	/* Create renderer */
	debugRenderer = new Box2DDebugRenderer();

	/*
	 * Define camera viewport. Box2D uses meters internally so the camera
	 * must be defined also in meters. We set a desired width and adjust
	 * height to different resolutions.
	 */
	camera = new OrthographicCamera(20,
			20 * (Gdx.graphics.getHeight() / (float) Gdx.graphics
					.getWidth()));

	/* Create the ball */
	Shape shape = Box2DFactory.createCircleShape(1);
	FixtureDef fixtureDef = Box2DFactory.createFixture(shape, 2.5f, 0.25f,
			0.75f, false);
	Box2DFactory.createBody(world, BodyType.DynamicBody, fixtureDef,
			new Vector2(5, 0));

	/* Create the box */
	shape = Box2DFactory.createBoxShape(0.5f, 0.5f, new Vector2(0, 0), 0);
	fixtureDef = Box2DFactory.createFixture(shape, 1, 0.5f, 0.5f, false);
	Box2DFactory.createBody(world, BodyType.StaticBody, fixtureDef,
			new Vector2(0, 0));

	/* Create the walls */
	walls = Box2DFactory.createWalls(world, camera.viewportWidth,
			camera.viewportHeight, 1);

	world.setContactListener(this);
}
 
Example 9
Source File: BuoyancySample.java    From Codelabs with MIT License 4 votes vote down vote up
@Override
public void show() {
	/*
	 * This line is found in every sample but is not necessary for the
	 * sample functionality. calls Sample.show() method. That method set the
	 * sample to receive all touch and key input events. Also prevents the
	 * app from be closed whenever the user press back button and instead
	 * returns to main menu.
	 */
	super.show();

	/*
	 * Create world with a common gravity vector (9.81 m/s2 downwards force)
	 * and tell world that we want objects to sleep. This last value
	 * conserves CPU usage.
	 */
	world = new World(new Vector2(0, -9.81f), true);

	/* Create renderer */
	debugRenderer = new Box2DDebugRenderer();

	/*
	 * Define camera viewport. Box2D uses meters internally so the camera
	 * must be defined also in meters. We set a desired width and adjust
	 * height to different resolutions.
	 */
	camera = new OrthographicCamera(20,
			20 * (Gdx.graphics.getHeight() / (float) Gdx.graphics
					.getWidth()));

	/*
	 * Next line must remain commented because we do this in its parent (See
	 * Sample class). In case you are not using Sample class, uncomment this
	 * line to set input processor to handle events.
	 */
	// Gdx.input.setInputProcessor(this);

	Box2DFactory.createWalls(world, camera.viewportWidth,
			camera.viewportHeight, 1);

	/* Create the water */
	Shape shape = Box2DFactory.createBoxShape(
			(camera.viewportWidth / 2 - 1),
			(camera.viewportHeight / 2 - 2) / 2, new Vector2(0, 0), 0);
	FixtureDef fixtureDef = Box2DFactory.createFixture(shape, 1, 0.1f, 0,
			true);
	Body water = Box2DFactory.createBody(world, BodyType.StaticBody,
			fixtureDef, new Vector2(0,
					-(camera.viewportHeight / 2 - 1) / 2 - 0.5f));

	/*
	 * Create a buoyancy controller using the previous body as a fluid
	 * sensor
	 */
	buoyancyController = new BuoyancyController(world, water
			.getFixtureList().first());

	world.setContactListener(this);
}
 
Example 10
Source File: EntityFactory.java    From ninja-rabbit with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Creates a new instance of {@link Collectible}, defining its graphical, audio and physical
 * properties.
 *
 * @param world
 *            The Box2D {@link World} onto which to create the {@link Body} and {@link Fixture}
 *            of the {@link Entity}.
 * @param assets
 *            The {@link AssetManager} from where to extract the graphical and audio resources.
 *            Those resources should be loaded in the manager before calling this method.
 * @return A ready to use instance of a new {@link Collectible}.
 */
public static Entity createCollectible(final World world, final AssetManager assets) {
	PhysicsProcessor physics = new CarrotPhysicsProcessor();
	CONTACT_LISTENER.add(physics);
	world.setContactListener(CONTACT_LISTENER);
	GraphicsProcessor graphics = new CarrotGraphicsProcessor(assets);
	AudioProcessor audio = new CarrotAudioProcessor(assets);
	return new Collectible(graphics, physics, audio);
}