Java - Superclass Fields Not Properly Being Changed - java

I have two classes, Entity and Ship where Ship extends Entity. In my entity class I have a private field speed. In my ship class I have a update method that is simply trying to increment speed by saying current speed + acceleration times a delta time.
Here is Entity:
private float height, rotation, speed, width;
private Sprite sprite;
private Vector2 origin, position;
public Entity (float x, float y) { position = new Vector2 (x, y); }
public Entity (float x, float y, Texture texture)
{
this (x, y);
if (texture != null)
{
sprite = new Sprite (texture);
width = sprite.getWidth ();
height = sprite.getHeight ();
origin = new Vector2 (x + width / 2f, y + height / 2f);
}
else
{
sprite = null;
origin = position;
}
}
public Entity (float x, float y, float rotation, Texture texture)
{
this (x, y, texture);
this.rotation = rotation;
}
public Entity (float x, float y, float rotation, float speed, Texture texture)
{
this (x, y, rotation, texture);
this.speed = speed;
}
public float getHeight () { return height; }
public float getRotation () { return rotation; }
public float getSpeed () { return speed; }
public float getWidth () { return width; }
public float getX () { return position.x; }
public float getY () { return position.y; }
public void setPosition (Vector2 vector) { position = vector; }
public void setRotation (float value) { rotation = value; }
public void setSpeed (float value) { speed = value; }
public void setSprite (Sprite sprite) { this.sprite = sprite; }
public void setX (float value) { position.x = value; }
public void setY (float value) { position.y = value; }
public Sprite getSprite () { return sprite; }
public Vector2 getOrigin () { return origin; }
public Vector2 getPosition () { return position; }
And here is the update() method of Ship:
setSpeed (getSpeed () + acceleration * delta);
System.out.println (getSpeed ());
What I expect to happen is that speed is increased by whatever acceleration * delta is. However, what happens is that speed is set equal to that value, not incremented. If I set the fields in Entity to static then my code works, but I feel that I shouldn't do that. I've also tried setting the fields to protected and the Entity class to abstract but I still get the same effect. I'm really at a loss as to what I'm doing wrong, unless setting the fields to static is correct?
EDIT:
The entire update method of Ship.
public void update (float delta)
{
// Updating the origin's position
getOrigin ().set (getX () + getWidth () / 2f, getY () + getHeight () / 2f);
updateTurrets (delta);
updateBullets (delta);
setSprite (updateSprite (delta));
//calculateRotateTo (moveTo);
setRotation (0f);
rotateTo = getRotation ();
if (getRotation () != rotateTo)
{
setRotation (rotateTo);
}
else if (getOrigin () != moveTo)
{
/*float currDistance = Utils.calculateDistance (originalPos, getOrigin ());
float totDistance = Utils.calculateDistance (originalPos, moveTo);
if (currDistance >= totDistance / 2f)
accelerating = false;
else
accelerating = true;
if (accelerating)
setSpeed (getSpeed () + acceleration * delta);
else
{
if (getSpeed () > 0f)
setSpeed (getSpeed () - acceleration * delta);
else
{
setSpeed (0f);
setPosition (moveTo);
}
}*/
setSpeed (getSpeed () + acceleration * delta);
System.out.println (getSpeed ());
}
}
EDIT #2: I did some extra testing and if I put a ship instance in the main render() method that LibGDX gives it works. Anywhere else however, it doesn't.

I believe I fixed it or at least as far as I can tell. Apparently saying static Ship ship = new Ship (); allowed for the fields to properly change without those fields also needing to be static.

Related

Java game with libGDX: my ship cant move to the right

I'm doing a Java Project that consists of making a "Space Invaders" clone. I'm starting with the ship movement, searching on stackOverflow I found this code:
if(Gdx.input.isKeyPressed(Input.Keys.LEFT) )
x -= Gdx.graphics.getDeltaTime() * PlayerSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) )
x += Gdx.graphics.getDeltaTime() * PlayerSpeed;
I use it to the playerShip(the class below):
public class PlayerShip extends Ship {
private Animator animator;
private float PlayerSpeed = 20.0f;
private int x,y;
public PlayerShip(SpriteBatch batch){
this.animator=new Animator(batch,"ship.png", 5, 2);
}
public void create(){
animator.create();
}
public void render(){
this.animator.render(this.x,this.y);
if(Gdx.input.isKeyPressed(Input.Keys.LEFT) )
x -= Gdx.graphics.getDeltaTime() * PlayerSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) )
x += Gdx.graphics.getDeltaTime() * PlayerSpeed;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
Game(main):
public class Game extends ApplicationAdapter {
private SpriteBatch batch;
private BackgroundManagement backgroundManagement;
private BitmapFont font;
private PlayerShip player;
private SmallShip smallShip;
#Override
public void create() {
Gdx.graphics.setWindowedMode(600, 800);
batch = new SpriteBatch();
player = new PlayerShip(batch);
smallShip = new SmallShip(batch);
player.create();
player.setX(300);
player.setY(100);
smallShip.create();
smallShip.setX(200);
smallShip.setY(400);
font = new BitmapFont(Gdx.files.internal("gamefont.fnt"),
Gdx.files.internal("gamefont.png"), false);
backgroundManagement = new BackgroundManagement(batch);
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
backgroundManagement.render();
player.render();
smallShip.render();
batch.end();
}
#Override
public void dispose() {
batch.dispose();
}
}
When trying on my code, the ship didn't move to the right, I had tried various solutions but i didn't found any, Any help is appreciated, thanks!
The position of the ship is an integer. Your increment is a float. You maybe have a decent graphics card which can render a simple game at e.g. 200+ fps continuous render (or more even could be crazy). In 200fps case the increment would be (1/200)*20 = 1/10 float.
integer += .1f
won't change the original integer.
Change your position to a float as well, then cast (or convert) to an integer when you need to actually render so x can increment very small values.

Why do i have to initialize the ball in Resize() method? - Libgdx

I'm making a simple Bouncing Ball game, even if i call the init() method via BouncingBall class constructor in Show() method of the BallScreen class, the ball isn't created. So to create a ball, i should call BouncingBall's init() method in Resize() method. Why? Isn't it supposed to be created in Show() method ?
Here is the code for Bouncing Ball
public class BouncingBall {
public static final float RADIUS_RATIO = 0.04f;
public static final float START_KICK = 500.0f;
private static final float KICK_INTERVAL = 3f;
private static final float DRAG = 1f;
private Vector2 position;
private Vector2 velocity;
float radius;
float lastKick;
public BouncingBall(Viewport viewport) {
init(viewport);
}
public void init(Viewport viewport) {
position = new Vector2();
position.x = viewport.getWorldWidth() / 2;
position.y = viewport.getWorldHeight() / 2;
velocity = new Vector2(0,0);
radius = RADIUS_RATIO * Math.min(viewport.getScreenWidth(), viewport.getScreenHeight());
startKick();
}
public void update(float delta, Viewport viewport) {
float elapsedSeconds = MathUtils.nanoToSec * (TimeUtils.nanoTime() - lastKick);
if (elapsedSeconds > KICK_INTERVAL) {
lastKick = TimeUtils.nanoTime();
startKick();
}
velocity.x -= delta * DRAG * velocity.x;
velocity.y -= delta * DRAG * velocity.y;
position.x += velocity.x * delta;
position.y += velocity.y * delta;
collision(radius,viewport);
}
public void collision(float radius, Viewport viewport) {
if (position.x + radius > viewport.getWorldWidth()) {
position.x = viewport.getWorldWidth() - radius;
velocity.x = -velocity.x;
}
if (position.x - radius < 0) {
position.x = radius;
velocity.x = -velocity.x;
}
if (position.y + radius > viewport.getScreenHeight()) {
position.y = viewport.getWorldHeight() - radius;
velocity.y = -velocity.y;
}
if (position.y - radius < 0) {
position.y = radius;
velocity.y = -velocity.y;
}
}
public void startKick() {
Random random = new Random();
float angle = random.nextFloat() * MathUtils.PI2;
velocity.x = START_KICK * MathUtils.cos(angle);
velocity.y = START_KICK * MathUtils.sin(angle);
}
public void render(ShapeRenderer renderer) {
renderer.setColor(Color.RED);
renderer.circle(position.x, position.y, radius);
}
}
Here is the Screen Class for Bouncing Ball
public class BallScreen extends ScreenAdapter {
private static final float WORLD_SIZE = 480f;
private static final String TAG = BallScreen.class.getSimpleName();
private BouncingBall ball;
private Viewport viewport;
private ShapeRenderer renderer;
#Override
public void show() {
Gdx.app.log(TAG, "Show");
viewport = new FitViewport(WORLD_SIZE, WORLD_SIZE);
renderer = new ShapeRenderer();
ball = new BouncingBall(viewport);
}
#Override
public void resize(int width, int height) {
Gdx.app.log(TAG, "resize" + width + " " + height);
viewport.update(width,height,true);
ball.init(viewport);
}
#Override
public void dispose() {
Gdx.app.log(TAG, "dispose");
renderer.dispose();
}
#Override
public void render(float delta) {
viewport.apply();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.setProjectionMatrix(viewport.getCamera().combined);
renderer.begin(ShapeType.Filled);
ball.update(delta, viewport);
ball.render(renderer);
renderer.end();
}
}
Problem is in this line :
radius = RADIUS_RATIO * Math.min(viewport.getScreenWidth(), viewport.getScreenHeight());
When you create FitViewPort and pass to BouncingBall, at that time viewport having only worldWidth and worldHeight that is what you set 480. At that time screenwidth and screenheight of viewport is zero so your radius initialise with zero value.
But After update() method if I call init() method :
viewport.update(width,height,true); // this method set value to screenwidth/height
when you call update method on viewport after that screenwidth and screenheight of viewport having some value according to what type of ViewPort you're using.
After update() if I call ball.init(viewport); then radius is not zero value so that ball is visible on screen.

Moving circle towards touched point

i'm trying to move a circle to the point i touch in my running app. I want to see the circle moving along a path towards this point i touch.
I have three classes:
public class Drawing extends View{
Context ctx;
static Circle c1;
private float circleCenterX = 100;
private float circleCenterY = 100;
private float lerpX;
private float lerpY;
private float time = 25;
private float frames = 100;
public Drawing(Context context) {
super(context);
this.ctx = context;
c1 = new Circle (165, 350, 33);
}
public void update(float x, float y) {
this.circleCenterX = x;
this.circleCenterY = y;
}
protected void onDraw (android.graphics.Canvas canvas){
Paint p = new Paint();
p.setColor(Color.GREEN);
lerpX = (circleCenterX - c1.getX()) * (time / frames) + c1.getX();
lerpY = (circleCenterY - c1.getY()) * (time / frames) + c1.getY();
canvas.drawCircle(lerpX, lerpY, c1.getR(), p);
c1.setX(lerpX);
c1.setY(lerpY);
}
public class Circle {
private float x;
private float y;
private float r;
public Circle(float x, float y, float r) {
super();
this.x = x;
this.y = y;
this.r = r;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getR() {
return r;
}
public void setR(float r) {
this.r = r;
}`
public class Game extends Activity implements OnTouchListener {
Drawing d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
d=new Drawing(this);
setContentView(d);
d.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent me) {
d.update(me.getX(), me.getY());
d.invalidate();
return true;
}
I think i will need something like a while or for loop to increment the x and y coords and or maybe need a speed value?!
Maybe im totally wrong and its a lot of more math to get it.
Thanks for your help
Cheers
Every time onDraw is called you need to move the circle a bit. The easiest way is just to move a certain number of pixels each time it's called.
To be able to do this you need to keep track of:
Where the animation started
Where you want the animation to end
Use linear interpolation to calculate the position of the circle in each onDraw call

LibGDX: How to get the same coordinates in tiled map for tile with and without zoom

I am a beginner with LibGDX. I am trying to create an android game based fixed size tiled map (33x21 tiles). Tiles I am using are 32x32px. So far I managed to load the map created with Tiled and add touch gestures like zoom in/out and panning. The game character movement will be turn based tile by tile, so I need to have a possibility to select specific tile in order to perform some action. I tried solution from here: LibGDX: How to make tiled map tiles clickable? and it works perfectly fine, until the screen is not zoomed in.
Without zoom, the left-bottom corner coordinates shows that it is (0,0), which is correct. When I zoom in, the left-bottom corner of the visible part of the map instead of keeping it's correct coordinates (i.e. (480, 320)) it becomes (0,0) again. I tried to use camera.unproject(Vector3), but I was unsuccessful. Probably used it wrong. I am also not really convinced, that the way in which I try to get tiles is the most appropriate one. Can you help me get tiles coordinates properly? Below is the code that I am using:
public class TiledTest extends ApplicationAdapter {
public TiledMap tiledMap;
OrthographicCamera camera;
TiledMapRenderer tiledMapRenderer;
GestureDetector gesture;
InputMultiplexer myInputMultiplexer;
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
public static final float PAN_RATE = (float) 0.01;
private static final float ZOOM_SPEED = (float) 0.009;
int columns, rows;
TiledMapTileLayer grid_layer;
#Override
public void create () {
gesture =new GestureDetector(new MyGestureListener());
myInputMultiplexer = new InputMultiplexer();
float unitScale = 1 / 32f;
camera = new OrthographicCamera();
camera.setToOrtho(true, 33,21);
tiledMap = new TmxMapLoader().load("tiled_map.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap, unitScale);
grid_layer = (TiledMapTileLayer)tiledMap.getLayers().get(0);
Stage stage = new TiledMapStage(tiledMap);
myInputMultiplexer.addProcessor(gesture);
myInputMultiplexer.addProcessor(stage);
Gdx.input.setInputProcessor(myInputMultiplexer);
}
#Override
public void render () {
tiledMapRenderer.setView(camera);
tiledMapRenderer.render();
camera.update();
}
public class TiledMapActor extends Actor {
private TiledMapTileLayer.Cell cell;
public TiledMapActor(TiledMap tileMap, TiledMapTileLayer tiledLayer, TiledMapTileLayer.Cell cell) {
tiledMap = tileMap;
grid_layer = tiledLayer;
this.cell = cell;
}
}
public class TiledMapClickListener extends ClickListener {
private TiledMapActor actor;
public TiledMapClickListener(TiledMapActor actor) {
this.actor = actor;
}
#Override
public void clicked(InputEvent event, float x, float y) {
int a = (int) actor.getX();
int b = (int) actor.getY();
System.out.println(actor.cell + " has been clicked.");
System.out.println("x = " + a + "y = " + b );
}
}
public class TiledMapStage extends Stage {
private TiledMap tiledMap;
public TiledMapStage(TiledMap tiledMap) {
this.tiledMap = tiledMap;
for (MapLayer layer : tiledMap.getLayers()) {
TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;
createActorsForLayer(tiledLayer);
}
}
private void createActorsForLayer(TiledMapTileLayer tiledLayer) {
for (int x = 0; x <= tiledLayer.getWidth(); x++) {
for (int y = 0; y < tiledLayer.getHeight(); y++) {
TiledMapTileLayer.Cell cell = tiledLayer.getCell(x, y);
TiledMapActor actor = new TiledMapActor(tiledMap, tiledLayer, cell);
actor.setBounds(x * tiledLayer.getTileWidth(), y * tiledLayer.getTileHeight(), tiledLayer.getTileWidth(),
tiledLayer.getTileHeight());
addActor(actor);
EventListener eventListener = new TiledMapClickListener(actor);
actor.addListener(eventListener);
}
}
}
}
public void resize(float width, float height) {
}
public class MyGestureListener implements GestureListener{
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
return false;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
float effectiveViewportWidth = camera.viewportWidth * camera.zoom;
float effectiveViewportHeight = camera.viewportHeight * camera.zoom;
camera.position.x = MathUtils.clamp(camera.position.x, effectiveViewportWidth / 2f, 33 - effectiveViewportWidth / 2f);
camera.position.y = MathUtils.clamp(camera.position.y, effectiveViewportHeight / 2f, 21 - effectiveViewportHeight / 2f);
if (camera.zoom < 1) {
camera.translate(-deltaX * PAN_RATE, -deltaY * PAN_RATE, 0);
camera.update();
}
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
//Gdx.app.log("Text", "panstop");
return false;
}
#Override
public boolean zoom (float originalDistance, float currentDistance){
float ratio = originalDistance/currentDistance;
camera.zoom += ZOOM_SPEED * ratio;
if (camera.zoom < 0.3)
{
camera.zoom = (float) 0.3;
}
else if (camera.zoom > 1)
{
camera.zoom = 1;
}
System.out.println(camera.zoom);
return false;
}
#Override
public boolean pinch (Vector2 initialFirstPointer, Vector2 initialSecondPointer, Vector2 firstPointer, Vector2 secondPointer){
camera.zoom -= .01;
camera.update();
return false;
}
}
}
So you want to transfer the screen coordinates to world coordinates.
For example:
#Override
public void clicked(InputEvent event, float x, float y) {
Vector3 touch = new Vector3(x, y, 0);
camera.unproject(touch);
System.out.println("Screen coordinates translated to world coordinates: "
+ "X: " + touch.x + " Y: " + touch.y);
}
}
Above clicked function does not worked for me, but you led me to the answer. I dumped whole assigning actors for tiles and used camera.unproject in MyGestureListener in touchDown.
If someone is interested I just leave it here :)
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
Vector3 temp_coord = new Vector3(x,y,0);
Vector3 coords = camera.unproject(temp_coord);
x =(int) coords.x;
y =(int) coords.y;
writerX = x;
writerY = y;
System.out.println("Screen coordinates translated to world coordinates: "
+ "X: " + x + " Y: " + y);
return false;
}

Wrong coordinates for different objects

In short:
I create Polygon object with a help of this method:
public static float[][] getPolygonArrays(float cx, float cy, float R, int sides) {
float[] x = new float[sides];
float[] y = new float[sides];
double thetaInc = 2 * Math.PI / sides;
double theta = (sides % 2 == 0) ? thetaInc : -Math.PI / 2;
for (int j = 0; j < sides; j++) {
x[j] = (float) (cx + R * Math.cos(theta));
y[j] = (float) (cy + R * Math.sin(theta));
theta += thetaInc;
}
return new float[][]{x, y};
}
and merge it to one dimension array with:
public static float[] mergeCoordinates(float[][] vertices) throws Exception {
if (vertices.length != 2 || vertices[0].length != vertices[1].length) throw new Exception("No valid data");
ArrayList<Float> mergedArrayList = new ArrayList<Float>();
float[] mergedArray = new float[vertices[0].length * 2];
for(int i = 0; i < vertices[0].length; i++) {
mergedArrayList.add(vertices[0][i]);
mergedArrayList.add(vertices[1][i]);
}
int i = 0;
for (Float f : mergedArrayList) {
mergedArray[i++] = (f != null ? f : Float.NaN);
}
return mergedArray;
}
I use 0 as value for X and Y for all newly created Polygons (named in code as Platform). And result of method mergeCoordinates i pass to method setVertices of Polygon object.
After this step i do setPosition with x = Gdx.graphics.getWidth()/2 and y = Gdx.graphics.getHeight()/2. Polygons are positioned good, right on the game screen center.
Than i create a new one Polygon, which must use origin coordinates from first Polygon object, this new polygon i named Figure. To set origin coordinates i use method setOrigin of Polygon class, and use X and Y of Platform Polygon object.
When i run method rotate of Platform Polygon object i also rotate Figure Polygon object, and Figure must rotate around origin point, center of Platform. But it does not.
Figure do rotation around bottom right corner.
For example:
my screen size is 640 x 480. Center point will be 320 x 240. This is X and Y of Platform Polygon object, i checked it with getX and getY of Polygon. I create Figure at 0,0, do setPosition(320, 200) (this is preferred orbit distance for figure to platform). And Figure positioned also good.
I run setOrigin(320, 240) for Figure Polygon Object.
I run rotate for Figure object. And it somehow think that right bottom corner have coordinates x = 320 and y = 240 and do rotation around this point.
Any could help me to solve this problem?
More details on problem you can find below(details, images, gifs, schemes and also sources).
More detailed part starts here
i'm trying to understand how coordinate system in libgdx work, cause i have a problem with positioning objects in game world.
I created simple application, with one big Red Polygon object(Platform in code),
10 White Triangle Polygons(Sector in code) which are included into big polygon object and inherits it's behavior(such like rotate, moveTo and etc).
Than i added inside each Sector one Green Polyline(Direction in code) from first vertice of Sector Polygon to midle point of the opposite side to first point.
This is technical line and i will use it's vertices(coordinates of two points) to move small Red Polygon Object(Figure in code), from center to oposite side to center point of Sector.
When i click on Stage and click coordinates are inside Platform i rotate it to the left or to the right(depends on where click was made). On rotate all Sectors and technical lines are rotated correctly.
http://i.imgur.com/s5xaI8j.gif
(670Kb)
As you can see on gif, figures rotates around theire's center point. I found that Polygon class has method setOrigin(float x, float y) and in annotation to this method said next:
/** Sets the origin point to which all of the polygon's local vertices
are relative to. */
So i tried to use this method, set origin X of Figure as center X of Platform and origin Y as center Y of Platform, and tried to rotate Platform.
http://i.imgur.com/pXpTuQi.gif
(1.06Mb)
As you can see, Figure polygon think that his origin coordinates are at right bottom corner. And Figure do rotation around right bottom corner.
I changed origin to next values: x = 50 and y = 50, here is a result:
http://i.imgur.com/Iajb9sN.gif
(640Kb)
I cannot get why it behave like that. What should i change in my logic?
I have not much classes in my project. I removed all imports and getters/setter to reduce amount of lines.
If it is necessary i could provide entire project.
GameScreen code:
public class GameScreen extends DefaultScreen {
private final GameWorld world;
private final GameRenderer renderer;
public GameScreen() {
world = new GameWorld();
renderer = new GameRenderer(world);
}
#Override
public void render(float delta) {
world.update(delta);
renderer.render();
}
#Override
public void resize(int width, int height) {
world.resize(width, height);
}
}
GameWorld code:
public class GameWorld {
private ArrayList < Platform > platforms = new ArrayList < Platform > ();
private OrthographicCamera camera;
private Stage stage;
private Array < Figure > activeFigures;
private Pool < Figure > figuresPool;
private long lastFigureTime = TimeUtils.nanoTime();
public GameWorld() {
setCamera(new OrthographicCamera());
getCamera().setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
setStage(new Stage());
getStage().setViewport(new ScreenViewport(getCamera()));
initializePools();
createPlatforms();
getStage().addListener(new InputListener() {
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
float degrees = Config.PLATFORM_ROTATE_DEGREES;
if (x <= Gdx.graphics.getWidth() / 2) {
degrees *= -1;
}
int i = getPlatforms().size();
while (i-- > 0) {
Platform platform = getPlatforms().get(i);
if (!platform.isLocked() && platform.isRotatable() && platform.getShape().getPolygon().contains(x, y)) {
platform.addAction(Actions.rotateBy(degrees, 1, Interpolation.bounceOut));
break;
}
}
return true;
}
});
Gdx.input.setInputProcessor(getStage());
}
private void initializePools() {
setActiveFigures(new Array < Figure > ());
setFiguresPool(new Pool < Figure > () {#Override
protected Figure newObject() {
return new Figure();
}
});
}
private void createPlatforms() {
float max = Gdx.graphics.getHeight() / (Gdx.graphics.getWidth() / (Gdx.graphics.getWidth() / 2));
float x = Gdx.graphics.getWidth() / 2;
float y = Gdx.graphics.getHeight() / 2;
float sides = 10f;
Color color = Color.RED;
createPlatform(x, y, max * Config.THIRD_PLATFORM_RADIUS_MULTIPLIER, sides, color, true, false, false, null);
}
private Platform createPlatform(float x, float y, float radius, float sides, Color color, boolean rotatable, boolean locked, boolean isEmpty, Platform relatedTo) {
Platform platform = new Platform(0, 0, radius, sides, color, isEmpty, this);
platform.moveTo(x, y);
platform.setRotatable(rotatable);
platform.setLocked(locked);
getPlatforms().add(platform);
getStage().addActor(platform);
if (relatedTo != null) {
relatedTo.addRelation(platform);
}
return platform;
}
private Figure createFigure(float x, float y) {
Figure figure = getFiguresPool().obtain();
figure.init(this, 0, 0, 10f, 4f, Color.DARK_GRAY);
figure.moveTo(x, y);
getActiveFigures().add(figure);
getStage().addActor(figure);
return figure;
}
public void spawnFigure() {
if (getActiveFigures().size >= 10) return;
if (TimeUtils.nanoTime() - getLastFigureTime() <= 2000000000) return;
Platform platform = null;
for (Platform p: getPlatforms()) {
if (!p.isEmpty()) {
platform = p;
break;
}
}
if (platform == null) {
setLastFigureTime(TimeUtils.nanoTime());
return;
}
Sector sector = platform.getSectors().get(MathUtils.random(platform.getSectors().size() - 1));
float x = platform.getX();
float y = platform.getY();
Figure figure = createFigure(x, y);
figure.origin(x, y);
x = sector.getDirection().getTransformedVertices()[2];
y = sector.getDirection().getTransformedVertices()[3];
figure.addAction(Actions.moveTo(x, y, 1));
setLastFigureTime(TimeUtils.nanoTime());
}
public void update(float delta) {
updatePlatforms(delta);
updateFigures(delta);
spawnFigure();
}
private void updatePlatforms(float delta) {
for (Platform platform: getPlatforms()) {
platform.update(delta);
}
}
private void updateFigures(float delta) {
Figure figure;
int figures = getActiveFigures().size;
for (int i = figures; --i >= 0;) {
figure = getActiveFigures().get(i);
if (figure.isAlive() == false) {
getActiveFigures().removeIndex(i);
getFiguresPool().free(figure);
} else {
figure.update(delta);
}
}
}
public void resize(int width, int height) {
getCamera().setToOrtho(true, width, height);
getStage().getViewport().update(width, height, true);
for (Platform platform: getPlatforms()) {
platform.resize(true, width, height);
}
for (Figure figure: getActiveFigures()) {
figure.resize(true, width, height);
}
}
}
GameRenderer code:
public class GameRenderer {
private ShapeRenderer shapeRenderer;
private GameWorld world;
private SpriteBatch spriteBatch;
public GameRenderer(GameWorld world) {
setWorld(world);
setShapeRenderer(new ShapeRenderer());
getShapeRenderer().setProjectionMatrix(getWorld().getCamera().combined);
setSpriteBatch(new SpriteBatch());
getSpriteBatch().setProjectionMatrix(getWorld().getCamera().combined);
}
public void render() {
Gdx.gl.glClearColor(0f, 0.2f, 0.4f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
getWorld().getCamera().update();
getSpriteBatch().setProjectionMatrix(getWorld().getCamera().combined);
getShapeRenderer().setProjectionMatrix(getWorld().getCamera().combined);
getWorld().getStage().act(Gdx.graphics.getDeltaTime());
getWorld().getStage().draw();
renderGameObjects();
}
private void renderGameObjects() {
renderPlatforms();
renderFigures();
}
private void renderFigures() {
getShapeRenderer().begin(ShapeRenderer.ShapeType.Line);
for (Figure figure: getWorld().getActiveFigures()) {
figure.render(getSpriteBatch(), getShapeRenderer());
}
getShapeRenderer().end();
}
private void renderPlatforms() {
getShapeRenderer().begin(ShapeRenderer.ShapeType.Line);
for (Platform platform: world.getPlatforms()) {
platform.render(getSpriteBatch(), getShapeRenderer());
}
getShapeRenderer().end();
}
}
Platform code:
public class Platform extends GameObject {
private ArrayList < Sector > sectors = new ArrayList < Sector > ();
private ArrayList < Platform > relations = new ArrayList < Platform > ();
private boolean rotatable = true;
private boolean locked = false;
private void initialize(float cx, float cy, float radius, float sides, Color color) {
setPosition(cx, cy);
setRadius(radius);
setShape(ShapeType.POLYGON.getInstance(new float[] {
cx, cy, radius, sides
}, color));
}
public Platform(float cx, float cy, float radius, float sides, Color color, boolean isEmpty, GameWorld gameWorld) {
setGameWorld(gameWorld);
initialize(cx, cy, radius, sides, color);
setEmpty(isEmpty);
if (!isEmpty()) {
generateSectors();
}
}
private void generateSectors() {
float[] vertices = getShape().getVertices();
for (int i = 0; i < vertices.length; i += 2) {
try {
Color color = Color.WHITE;
if (i + 3 > vertices.length) {
getSectors().add(new Sector(new float[] {
getX(), getY(), vertices[i], vertices[i + 1], vertices[0], vertices[1]
}, color, this, i / 2));
} else {
getSectors().add(new Sector(new float[] {
getX(), getY(), vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 3]
}, color, this, i / 2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void rotateBy(float degrees) {
setRotation(degrees);
getShape().rotate(degrees);
for (Sector sector: getSectors()) {
sector.rotate(degrees);
}
for (Platform platform: getRelations()) {
platform.rotateBy(degrees);
}
for (Figure figure: getGameWorld().getActiveFigures()) {
figure.rotate(degrees);
}
}
#Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
getShape().moveTo(x, y);
for (Sector sector: getSectors()) {
sector.moveTo(x, y);
}
for (Platform platform: getRelations()) {
platform.moveTo(x, y);
}
}
public void addRelation(Platform platform) {
if (platform.equals(this)) return;
getRelations().add(platform);
}
#Override
public void update(float delta) {
for (Sector sector: getSectors()) {
sector.update(delta);
}
}
#Override
public void dispose() {
for (Sector sector: getSectors()) {
sector.dispose();
}
}
#Override
public void render(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer) {
render(spriteBatch);
if (Config.DEBUG_LAYOUTS) render(shapeRenderer);
for (Sector sector: getSectors()) {
sector.render(spriteBatch, shapeRenderer);
}
}
private void render(ShapeRenderer shapeRenderer) {
shapeRenderer.setColor(getShape().getColor());
shapeRenderer.polygon(getShape().getVertices());
}
public void resize(boolean reposition, int width, int height) {
if (reposition) {
moveTo(width / 2, height / 2);
}
}
}
Sector code:
public class Sector extends GameObject {
private Polyline direction;
private float[] vertices;
private Platform platform;
private int sectorId;
public Sector(float[] vertices, Color color, Platform platform, int sectorId) throws Exception {
setSectorId(sectorId);
setVertices(vertices);
initialize(vertices, color, platform);
}
private void createDirection() {
float[] vertices = getShape().getPolygon().getVertices();
float x1 = vertices[0];
float y1 = vertices[1];
float x2 = (vertices[2]+vertices[4])/2;
float y2 = (vertices[3]+vertices[5])/2;
setDirection(new Polyline(new float[]{ x1, y1, x2, y2 }));
}
public Sector(float[] vertices, Color color, boolean isEmpty) throws Exception {
initialize(vertices, color);
setEmpty(isEmpty);
}
private void initialize(float[] vertices, Color color) throws Exception {
if (vertices.length != 6) {
throw new Exception("Sector constructor expects 6 vertices");
}
setShape(ShapeType.TRIANGLE.getInstance(vertices, color));
createDirection();
}
private void initialize(float[] vertices, Color color, Platform platform) throws Exception {
if (vertices.length != 6) {
throw new IllegalArgumentException("Sector constructor expects 6 vertices");
}
setShape(ShapeType.TRIANGLE.getInstance(vertices, color));
setPlatform(platform);
createDirection();
}
public void rotate(float degrees) {
getShape().rotate(degrees);
getDirection().rotate(degrees);
}
#Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
getShape().moveTo(x, y);
getDirection().setPosition(x, y);
}
#Override
public void render(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer) {
render(spriteBatch);
if (Config.DEBUG_LAYOUTS) render(shapeRenderer);
}
private void render(ShapeRenderer shapeRenderer) {
shapeRenderer.setColor(getShape().getColor());
shapeRenderer.polygon(getShape().getVertices());
shapeRenderer.setColor(Color.GREEN);
shapeRenderer.line(getDirection().getTransformedVertices()[0], getDirection().getTransformedVertices()[1], getDirection().getTransformedVertices()[2], getDirection().getTransformedVertices()[3]);
}
}
Figure code:
public class Figure extends GameObject {
private GameWorld world;
public void init(GameWorld world, float cx, float cy, float radius, float sides, Color color) {
super.init();
setWorld(world);
initialize(cx, cy, radius, sides, color);
}
private void initialize(float cx, float cy, float radius, float sides, Color color) {
super.moveTo(cx, cy);
setRadius(radius);
setShape(ShapeType.POLYGON.getInstance(new float[] {
cx, cy, radius, sides
}, color));
}
#Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
getShape().moveTo(x, y);
}
#Override
public void setPosition(float x, float y) {
if (!isAllowedToFlyFuther()) {
clearActions();
return;
}
moveTo(x, y);
}
private boolean isAllowedToFlyFuther() {
for (Figure figure: getWorld().getActiveFigures()) {
if (!figure.equals(this) && Intersector.overlapConvexPolygons(figure.getShape().getPolygon(), getShape().getPolygon())) {
return false;
}
}
return true;
}
#Override
public void reset() {
super.reset();
remove();
}
#Override
public void update(float delta) {}
private void render(SpriteBatch spriteBatch) {}
#Override
public void dispose() {}
#Override
public void render(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer) {
render(spriteBatch);
if (Config.DEBUG_LAYOUTS) render(shapeRenderer);
}
private void render(ShapeRenderer shapeRenderer) {
shapeRenderer.setColor(getShape().getColor());
shapeRenderer.polygon(getShape().getVertices());
}
public void rotate(float degrees) {
setRotation(degrees);
getShape().rotate(degrees);
}
public void origin(float originX, float originY) {
setOrigin(originX, originY);
getShape().setOrigin(originX, originY);
}
public void resize(boolean reposition, int width, int height) {
if (reposition) {
//TODO: implement reposition for figures
}
}
}
GameObject code:
public abstract class GameObject extends Actor implements Poolable {
private int speed = 200;
private int baseSpeed = 200;
private boolean alive;
private float radius;
private GameWorld gameWorld;
private Shape shape;
private boolean empty = false;
public GameObject() {
setAlive(false);
}
public void init() {
setAlive(true);
}
public void reset() {
setAlive(false);
}
public abstract void update(float delta);
public abstract void render(SpriteBatch spriteBatch, ShapeRenderer shapeRenderer);
public abstract void dispose();
public void moveTo(float x, float y) {
super.setPosition(x, y);
}
}
Shape code:
public class Shape {
private Color color = new Color(Color.RED);
private float[] vertices;
private int sides;
private float radius;
private Polygon polygon = new Polygon();
public void rotate(float degrees) {
getPolygon().rotate(degrees);
setVertices(getPolygon().getTransformedVertices());
}
public void moveTo(float x, float y) {
getPolygon().setPosition(x, y);
setVertices(getPolygon().getTransformedVertices());
}
public void setOrigin(float originX, float originY) {
getPolygon().setOrigin(originX, originY);
setVertices(getPolygon().getTransformedVertices());
}
public void scale(float ratio) {
getPolygon().setScale(ratio, ratio);
setVertices(getPolygon().getTransformedVertices());
}
}
ShapeType code:
public enum ShapeType {
POLYGON {#Override
public Shape getInstance(float[] settings, Color color) {
try {
return new PolygonShape(settings, color);
} catch (Exception e) {
e.printStackTrace();
}
return new BaseShape();
}
},
TRIANGLE {#Override
public Shape getInstance(float[] settings, Color color) {
try {
return new TriangleShape(settings, color);
} catch (Exception e) {
e.printStackTrace();
}
return new BaseShape();
}
};
public abstract Shape getInstance(float[] settings, Color color);
}
PolygonShape code:
public class PolygonShape extends Shape {
public PolygonShape(float[] settings, Color color) throws Exception {
if (settings.length < 4) {
throw new IllegalArgumentException("Polygon shape constructor expects minimum 4 items in settings");
}
setSides((int) settings[3]);
setRadius(settings[2]);
setVertices(Utils.mergeCoordinates(Utils.getPolygonArrays(settings[0], settings[1], settings[2], (int) settings[3])));
getPolygon().setVertices(getVertices());
}
}
TriangleShape code:
public class TriangleShape extends Shape {
public TriangleShape(float[] settings, Color color) throws Exception {
if (settings.length < 6) {
throw new IllegalArgumentException("Triangle shape constructor expects minimum 6 items in settings");
}
setVertices(settings);
setColor(color);
getPolygon().setVertices(getVertices());
}
}
Utils code:
public class Utils {
public static float[] mergeCoordinates(float[][] vertices) throws Exception {
if (vertices.length != 2 || vertices[0].length != vertices[1].length) throw new Exception("No valid data");
ArrayList < Float > mergedArrayList = new ArrayList < Float > ();
float[] mergedArray = new float[vertices[0].length * 2];
for (int i = 0; i < vertices[0].length; i++) {
mergedArrayList.add(vertices[0][i]);
mergedArrayList.add(vertices[1][i]);
}
int i = 0;
for (Float f: mergedArrayList) {
mergedArray[i++] = (f != null ? f : Float.NaN);
}
return mergedArray;
}
public static float[][] getPolygonArrays(float cx, float cy, float R, int sides) {
float[] x = new float[sides];
float[] y = new float[sides];
double thetaInc = 2 * Math.PI / sides;
double theta = (sides % 2 == 0) ? thetaInc : -Math.PI / 2;
for (int j = 0; j < sides; j++) {
x[j] = (float)(cx + R * Math.cos(theta));
y[j] = (float)(cy + R * Math.sin(theta));
theta += thetaInc;
}
return new float[][] {
x, y
};
}
}
Config code:
public class Config {
public static final String LOG = TheGame.class.getSimpleName();
public static final boolean DEBUG_LAYOUTS = true;
public static final boolean SHOW_LOG = false;
public static final float PLATFORM_ROTATE_DEGREES = 36;
}
DesktopLauncher code:
public class DesktopLauncher {
public static void main(String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "The Game!";
config.width = 1920 / 3;
config.height = 1080 / 3;
new LwjglApplication(new TheGame(), config);
}
}
Project structure:
Platform object structure and dependencies:
Render objects workflow

Categories

Resources