Invalid coordinates for different objects

In short:

I am creating a Polygon object using 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 concatenate it into one dimensional 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 the value for X and Y for all newly created Polygons (named Platform in the code). And the result of the mergeCoordinates method I go to the setVertices method of the Polygon object.

After this step, I set Position with x = Gdx.graphics.getWidth () / 2 and y = Gdx.graphics.getHeight () / 2. Polygons are positioned well, right on the game screen.

Than I create a new Polygon which should use the original coordinates from the first Polygon object, this new polygon I named Figure. To set the origin coordinates, I use the setOrigin method of the Polygon class and use the X and Y of the Polygon Platform object.

When I run the Polygon Platform object rotation method, I also rotate the Polygon Figure object, and the figure should rotate around the origin point, in the center of the platform. But this is not the case.

Pattern: Rotate around the bottom right corner.

For example:

my screen size is 640 x 480. The center point will be 320 x 240. This is the X and Y of the Polygon Platform object, I checked it with getX and getY from Polygon. I create a drawing at 0,0, do setPosition (320, 200) (this is the preferred orbital distance for the shape to the platform). And the drawing is positioned just as well.

I am running setOrigin (320, 240) on a Polygon Figure object.

I am running rotation on a Figure object. And it somehow thinks that the bottom right corner has coordinates x = 320 and y = 240 and rotates around that point.

Anyone can help me solve this problem?

More details on the issue you can find below (details, images, gifs, schematics, as well as sources).

More details start here

I am trying to understand how the coordinate system in libgdx works because I have a problem with positioning objects in the game world. I have created a simple app with one big Red Polygon object (platform in code), Imgur

10 white triangle polygons (wedge in code) that are included in the large polygon object and inherit its behavior (for example, rotate, moveTo, etc.). Imgur

Then I added inside each sector one green polyline (direction in the code) from the first vertex of the sector polygon to the midpoint of the opposite side to the first point. Imgur

This is a technical line, and I will use its vertices (the coordinates of the two points) to move the small Red Polygon object (pictured in the code) from the center to the opposite side to the center point of the sector. Imgur

When I click on "Scene" and the coordinates of the click are inside the platform, I rotate it left or right (depending on where the click was made). When rotating, all sectors and technical lines rotate correctly. http://i.imgur.com/s5xaI8j.gif (670KB)

As you can see in the gif, the numbers rotate around the center point. I found that the Polygon class has a method setOrigin (float x, float y) and in the annotation to that method, which is given below:

/ ** Sets the starting point to which all local vertices of the polygon refer to. * /

So I tried this method, set the origin X of the shape to be the center of the X of the platform and the origin Y to the center of the Y of the platform, and tried to rotate the platform. http://i.imgur.com/pXpTuQi.gif (1.06MB)

As you can see fig. the polygon assumes that its original coordinates are in the lower right corner. And the drawing rotates around the bottom bottom corner.

I changed the start to the following values: x = 50 and y = 50, here is the result: http://i.imgur.com/Iajb9sN.gif (640KB)

I cannot understand why this is the case. What should I change in my logic?

I have few lessons in my project. I removed all imports and getters / setters to reduce the number of lines.

If necessary, I could provide the 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]);
    }
}

      

Picture 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);
    }
}

      

Form 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
        };
    }
}

      

Configuration 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: Imgur

Platform structure and dependencies: Imgur

Object rendering workflow Imgur

+3


source to share