com.me.mygdxgame.WallActor.java Source code

Java tutorial

Introduction

Here is the source code for com.me.mygdxgame.WallActor.java

Source

/*
Copyright (c) Philip Bliss, 2013
    
This file is provided under the Apache License, Version 2.0. See the file LICENSE for more.
 */
package com.me.mygdxgame;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.me.mygdxgame.GdxTest.WallPos;

public class WallActor extends Actor {
    protected Body body;
    private Rectangle bounds;
    private Fixture fixture;
    WallPos wallPos;
    private GdxTest gdxTest;

    public static float WALL_WIDTH_M = .001f;

    private Color wallColor = new Color(0.1f, 0.1f, 1f, .75f);
    boolean dead = false;

    public WallActor(GdxTest gdxTest, Vector2 screenSize, WallPos wallPos) {
        this.gdxTest = gdxTest;
        this.wallPos = wallPos;

        switch (wallPos) {
        case Bottom:
            bounds = new Rectangle(0, 0, screenSize.x, gdxTest.getPixelsPerMeter().y * WALL_WIDTH_M);
            break;
        case Left:
            bounds = new Rectangle(0, 0, gdxTest.getPixelsPerMeter().x * WALL_WIDTH_M, screenSize.y);
            break;
        case Right:
            bounds = new Rectangle(screenSize.x - gdxTest.getPixelsPerMeter().x * WALL_WIDTH_M, 0,
                    gdxTest.getPixelsPerMeter().x * WALL_WIDTH_M, screenSize.y);
            break;
        case Top:
            bounds = new Rectangle(0, screenSize.y - gdxTest.getPixelsPerMeter().y * WALL_WIDTH_M, screenSize.x,
                    gdxTest.getPixelsPerMeter().y * WALL_WIDTH_M);
            break;
        }

        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.StaticBody;

        body = gdxTest.world.createBody(bodyDef);

        PolygonShape rectangleShape = new PolygonShape();
        boundsToM(bounds, rectangleShape);

        fixture = body.createFixture(rectangleShape, 1f);
    }

    private void boundsToM(Rectangle boundsPix, PolygonShape rectangleShape) {
        Vector2 halfSizeM = new Vector2(), centerM = new Vector2();
        boundsPix.getPosition(centerM);
        centerM.div(gdxTest.getPixelsPerMeter());
        boundsPix.getPosition(centerM);
        centerM.div(gdxTest.getPixelsPerMeter());

        rectangleShape.setAsBox(halfSizeM.x, halfSizeM.y, centerM, 0f);
    }

    public void drawBox(ShapeRenderer sr) {
        sr.setColor(wallColor);
        sr.box(bounds.x, bounds.y, 0, bounds.width, bounds.height, 0);
    }

    public Rectangle getRect() {
        return bounds;
    }

}