LibGdx Chess Board - java

I try to create a chess board, just the board in libGdx but for some reason, I can't.
I still miss two other rows in the chess. I will show you my code, maybe you can find the problem in my code, if not, I can easily accept another solution.
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.viewport.Viewport;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
private OrthographicCamera camera;
private OrthogonalTiledMapRenderer render;
private final static int width = 100, height = 80, layercount = 8;
private TiledMap map;
#Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(w, h);
Pixmap pixmap = new Pixmap(100, 80, Format.RGBA8888);
pixmap.setColor(Color.WHITE); // add your 1 color here
pixmap.fillRectangle(0, 0, 80, 80);
pixmap.setColor(Color.BLACK); // add your 2 color here
pixmap.fillRectangle(0, 0, 80, 80);
// the outcome is an texture with an blue left square and an red right
// square
Texture t = new Texture(pixmap);
TextureRegion reg1 = new TextureRegion(t, 0, 0, 80, 80);
TextureRegion reg2 = new TextureRegion(t, 80, 0, 80, 80);
TiledMap map = new TiledMap();
MapLayers layers = map.getLayers();
for (int l = 0; l < layercount; l++) {
TiledMapTileLayer layer = new TiledMapTileLayer(width, height, 80,
80);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Cell cell = new Cell();
if (y % 2!= 0) {
if (x % 2 != 0) {
cell.setTile(new StaticTiledMapTile(reg1));
} else {
cell.setTile(new StaticTiledMapTile(reg2));
}
} else {
if (x % 2 != 0) {
cell.setTile(new StaticTiledMapTile(reg2));
} else {
cell.setTile(new StaticTiledMapTile(reg1));
}
}
layer.setCell(x, y, cell);
}
}
layers.add(layer);
}
render = new OrthogonalTiledMapRenderer(map);
render.setView(camera);
camera.translate(Gdx.graphics.getWidth() / 2,
Gdx.graphics.getHeight() / 2);
}
#Override
public void dispose() {
render.dispose();
map.dispose();
}
private static final float movmentspeed = 5f;
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
render.setView(camera);
render.render();
if (Gdx.input.isKeyPressed(Keys.LEFT)) {
camera.translate(-movmentspeed, 0);
} else if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
camera.translate(movmentspeed, 0);
} else if (Gdx.input.isKeyPressed(Keys.UP)) {
camera.translate(0, movmentspeed);
} else if (Gdx.input.isKeyPressed(Keys.DOWN)) {
camera.translate(0, -movmentspeed);
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Here is my code. I need a solution to this as fast as possible if you can...

Your second call to
pixmap.setColor(Color.BLACK); // add your 2 color here
pixmap.fillRectangle(0, 0, 80, 80);
overwrites the colour set by the first because you are writing to the same area.
Within the nested loop iterating over the board, you could simplify finding the alternating cell type for the chessboard to
if ((x+(y*8)) % 2 = 0 ) {
//Cell is bottom left square color
} else {
//Cell is the other colour
}
Although its nice to generate the chess board for special effects later, you could also just import one from the tiled editor and then you can experiment more with how it looks. Tile map loaders absolutely not the pain you might imagine they are super short, literally a snippets worth, there is a written loader here
https://gamefromscratch.com/libgdx-tutorial-11-tiled-maps-part-1-simple-orthogonal-maps/
(also and not relevant this
Pixmap pixmap = new Pixmap(100, 80, Format.RGBA8888); is a larger region than you ever use.)
There is a no AI libGDX chess game here as well if you want to just extend with AI.
https://github.com/axlan/libgdx-chess

Related

How do I make a top down view with the ability to rotate with built in java graphics?

I'm trying to make a racing game with the top down view on a static player in the middle of the screen, so instead of moving the player through the map, the map would move around the player. Since it's a racing game, I wanted it to also be somewhat similar to a car, but I've been having trouble with rotating the map around the player and having that work with translations.
I've tried keeping track of the center by adding or subtracting from it, which is what I did for the translations, but it doesn't work with the rotate method. The rotate function wouldn't rotate about the player and instead would rotate the player around some other point, and the translations would snap to a different location from the rotations. I'm sure my approach is flawed, and I have read about layers and such, but I'm not sure what I can do with them or how to use them. Also, any recommendations as to how to use java graphics in general would be greatly appreciated!
This is what I have in my main:
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class game
{
public static void main(String []args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 1000;
final int FRAME_HEIGHT = 600;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Map b = new Map();
frame.add(b,BorderLayout.CENTER);
frame.setVisible(true);
b.startAnimation();
}
}
And this is the class that handles all the graphics
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Map extends JComponent implements Runnable, KeyListener
{
private int speed = 5;
private int xcenter = 500; // starts on player
private int ycenter = 300;
private double angle = 0.0;
private int[] xcords = {xcenter+10, xcenter, xcenter+20};
private int[] ycords = {ycenter-10, ycenter+20, ycenter+20};
private boolean moveNorth = false;
private boolean moveEast = false;
private boolean moveSouth = false;
private boolean moveWest = false;
public Map()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void startAnimation()
{
Thread t = new Thread(this);
t.start();
}
public void paintComponent(Graphics g)
{
g.fillPolygon(xcords, ycords, 3);
// move screen
if(moveNorth)
{
ycenter += speed;
g.translate(xcenter, ycenter);
}
else if(moveEast)
{
angle += ((1 * Math.PI/180) % (2 * Math.PI));
((Graphics2D) g).rotate(angle, 0, 0);
}
else if(moveSouth)
{
System.out.println(xcenter + ", " + ycenter);
ycenter -= speed;
((Graphics2D) g).rotate(angle, 0, 0);
g.translate(xcenter, ycenter);
}
else if(moveWest)
{
angle -= Math.toRadians(1) % (2 * Math.PI);
((Graphics2D) g).rotate(angle, 0, 0);
}
for(int i = -10; i < 21; i++)
{
g.drawLine(i * 50, -1000, i * 50, 1000);
g.drawLine(-1000, i * 50, 1000, i * 50);
}
g.drawOval(0, 0, 35, 35);
}
public void run()
{
while (true)
{
try
{
if(moveNorth || moveEast || moveSouth || moveWest)
{
repaint();
}
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
}
}
public void keyPressed(KeyEvent e)
{
if(e.getExtendedKeyCode() == 68) // d
{
moveEast = true;
}
else if(e.getExtendedKeyCode() == 87) // w
{
moveNorth = true;
}
else if(e.getExtendedKeyCode() == 65) // a
{
moveWest = true;
}
else if(e.getExtendedKeyCode() == 83) // s
{
moveSouth = true;
}
}
public void keyReleased(KeyEvent e)
{
moveNorth = false;
moveEast = false;
moveSouth = false;
moveWest = false;
}
public void keyTyped(KeyEvent e)
{
}
}
You have to keep in mind that transformations are compounding, so if you rotate the Graphics context by 45 degrees, everything painted after it will be rotated 45 degrees (around the point of rotation), if you rotate it again by 45 degrees, everything painted after it will be rotated a total of 90 degrees.
If you want to paint additional content after a transformation, then you either need to undo the transformation, or, preferably, take a snapshot of the Graphics context and dispose of it (the snapshot) when you're done.
You also need to beware of the point of rotation, Graphics2D#rotate(double) will rotate the Graphics around the point of origin (ie 0x0), which may not be desirable. You can change this by either changing the origin point (ie translate) or using Graphics2D#rotate(double, double, double), which allows you to define the point of rotation.
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class TestPane extends JPanel {
enum Direction {
LEFT, RIGHT;
}
protected enum InputAction {
PRESSED_LEFT, PRESSED_RIGHT, RELEASED_LEFT, RELEASED_RIGHT
}
private BufferedImage car;
private BufferedImage road;
private Set<Direction> directions = new TreeSet<>();
private double directionOfRotation = 0;
public TestPane() throws IOException {
car = ImageIO.read(getClass().getResource("/images/Car.png"));
road = ImageIO.read(getClass().getResource("/images/Road.png"));
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), InputAction.PRESSED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), InputAction.RELEASED_LEFT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), InputAction.PRESSED_RIGHT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), InputAction.RELEASED_RIGHT);
am.put(InputAction.PRESSED_LEFT, new DirectionAction(Direction.LEFT, true));
am.put(InputAction.RELEASED_LEFT, new DirectionAction(Direction.LEFT, false));
am.put(InputAction.PRESSED_RIGHT, new DirectionAction(Direction.RIGHT, true));
am.put(InputAction.RELEASED_RIGHT, new DirectionAction(Direction.RIGHT, false));
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (directions.contains(Direction.RIGHT)) {
directionOfRotation += 1;
} else if (directions.contains(Direction.LEFT)) {
directionOfRotation -= 1;
}
// No doughnuts for you :P
if (directionOfRotation > 180) {
directionOfRotation = 180;
} else if (directionOfRotation < -180) {
directionOfRotation = -180;
}
repaint();
}
});
timer.start();
}
protected void setDirectionActive(Direction direction, boolean active) {
if (active) {
directions.add(direction);
} else {
directions.remove(direction);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(213, 216);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
drawRoadSurface(g2d);
drawCar(g2d);
g2d.dispose();
}
protected void drawCar(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
int x = (getWidth() - car.getWidth()) / 2;
int y = (getHeight() - car.getHeight()) / 2;
g2d.drawImage(car, x, y, this);
g2d.dispose();
}
protected void drawRoadSurface(Graphics2D g2d) {
g2d = (Graphics2D) g2d.create();
// This sets the point of rotation at the center of the window
int midX = getWidth() / 2;
int midY = getHeight() / 2;
g2d.rotate(Math.toRadians(directionOfRotation), midX, midY);
// We then need to offset the top/left corner so that what
// we want draw appears to be in the center of the window,
// and thus will be rotated around it's center
int x = midX - (road.getWidth() / 2);
int y = midY - (road.getHeight() / 2);
g2d.drawImage(road, x, y, this);
g2d.dispose();
}
protected class DirectionAction extends AbstractAction {
private Direction direction;
private boolean active;
public DirectionAction(Direction direction, boolean active) {
this.direction = direction;
this.active = active;
}
#Override
public void actionPerformed(ActionEvent e) {
setDirectionActive(direction, active);
}
}
}
}

How to detect collisions between objects in LibGDX

This is my first post on stack overflow so I apologize in advance if I'm breaking any rules about posting, etc. I have been working on a an asteroids-esque shooting game and I can't figure out how to get the collision detection working between the rocks and the laser.
The source code can be found here. I had to make some changes to the update method of LevelScreen because the original code is dependent on using the BlueJ IDE. I found a fix in this post and got the collision working between the spaceship and the rocks.
The LevelScreen class
package com.mygdx.game;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import java.util.ArrayList;
public class LevelScreen extends BaseScreen {
private Spaceship spaceship;
private boolean gameOver;
private boolean rocksNeedRemoved;
private Rock toRemove;
private ArrayList<Rock> rocks;
private ArrayList<Laser> lasers;
public void initialize() {
gameOver = false;
toRemove = null;
rocksNeedRemoved = false;
BaseActor space = new BaseActor(0, 0, mainStage);
space.loadTexture("space.png");
space.setSize(800, 600);
BaseActor.setWorldBounds(space);
spaceship = new Spaceship(400, 300, mainStage);
rocks = new ArrayList<Rock>();
lasers = new ArrayList<Laser>();
rocks.add(new Rock(600, 500, mainStage));
rocks.add(new Rock(600, 300, mainStage));
rocks.add(new Rock(600, 100, mainStage));
rocks.add(new Rock(400, 100, mainStage));
rocks.add(new Rock(200, 100, mainStage));
rocks.add(new Rock(200, 300, mainStage));
rocks.add(new Rock(200, 500, mainStage));
rocks.add(new Rock(400, 500, mainStage));
lasers.add(new Laser(400, 500, mainStage));
}
public void update(float dt) {
//Code from book(Throws class not found error)
/*
for (BaseActor rockActor : BaseActor.getList(mainStage,
"Rock")) {
if (rockActor.overlaps(spaceship)) {
if (spaceship.shieldPower <= 0) {
Explosion boom = new Explosion(0, 0,
mainStage);
boom.centerAtActor(spaceship);
spaceship.remove();
spaceship.setPosition(-1000, -1000);
BaseActor messageLose = new BaseActor(0, 0,
uiStage);
messageLose.loadTexture("message-
lose.png");
messageLose.centerAtPosition(400, 300);
messageLose.setOpacity(0);
messageLose.addAction(Actions.fadeIn(1));
gameOver = true;
}
else {
spaceship.shieldPower -= 34;
Explosion boom = new Explosion(0, 0,
mainStage);
boom.centerAtActor(rockActor);
rockActor.remove();
}
}
for (BaseActor laserActor :
BaseActor.getList(mainStage, "Laser")) {
if (laserActor.overlaps(rockActor)) {
}
Explosion boom = new Explosion(0, 0,
mainStage);
boom.centerAtActor(rockActor);
laserActor.remove();
rockActor.remove();
}
}
if (!gameOver && BaseActor.count(mainStage, "Rock") ==
0) {
BaseActor messageWin = new BaseActor(0, 0,
uiStage);
messageWin.loadTexture("message-win.png");
messageWin.centerAtPosition(400, 300);
messageWin.setOpacity(0);
messageWin.addAction(Actions.fadeIn(1));
gameOver = true;
}
}
*/
// loop I used to get collision working between rocks
and spaceship
for (Rock each : rocks)
if (spaceship.overlaps(each) && !each.crashed &&
spaceship.shieldPower <= 0) {
Explosion boom = new Explosion(0, 0,
mainStage);
Explosion boom2 = new Explosion(0, 0,
mainStage);
boom.centerAtActor(spaceship);
boom2.centerAtActor(each);
spaceship.remove();
spaceship.setPosition(-1000, -1000);
each.crashed = true;
each.clearActions();
each.addAction(Actions.fadeOut(1));
each.addAction(Actions.after(Actions.removeActor()));
rocksNeedRemoved = true;
toRemove = each;
} else if (spaceship.overlaps(each) &&
!each.crashed) {
Explosion boom = new Explosion(0, 0,
mainStage);
boom.centerAtActor(each);
spaceship.shieldPower -= 34;
each.crashed = true;
each.clearActions();
each.addAction(Actions.fadeOut(1));
each.addAction(Actions.after(Actions.removeActor()));
rocksNeedRemoved = true;
toRemove = each;
}
//check for collision between rocks and lasers (Not
working correctly)
for (int i = rocks.size() - 1; i >= 0; i--) {
Rock rock = rocks.get(i);
for (int j = lasers.size() - 1; j >= 0; j--) {
Laser laser = lasers.get(j);
if(rock.getBounds().overlaps(laser.getBounds())) {
Explosion boom = new Explosion(0, 0,
mainStage);
boom.centerAtActor(rock);
rock.crashed = true;
rock.clearActions();
rock.addAction(Actions.fadeOut(1));
rock.addAction(Actions.after(Actions.removeActor()));
rocksNeedRemoved = true;
toRemove = rock;
}
}
}
}
//override default InputProcessor method
public boolean keyDown(int keycode) {
if (keycode == Keys.X)
spaceship.warp();
if (keycode == Keys.SPACE)
spaceship.shoot();
return false;
}
}
The Spaceship class.
package com.mygdx.game;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.math.MathUtils;
public class Spaceship extends BaseActor {
private Thrusters thrusters;
private Shield shield;
public int shieldPower;
public Spaceship(float x, float y, Stage s) {
super(x, y, s);
loadTexture("spaceship.png");
setBoundaryPolygon(8);
setAcceleration(100);
setMaxSpeed(100);
setDeceleration(10);
thrusters = new Thrusters(0, 0, s);
addActor(thrusters);
thrusters.setPosition(-thrusters.getWidth(),
getHeight() / 2 - thrusters.getHeight() / 2);
shield = new Shield(0, 0, s);
addActor(shield);
shield.centerAtPosition(getWidth() / 2, getHeight() /
2);
shieldPower = 100;
}
public void act(float dt) {
super.act(dt);
float degreesPerSecond = 160; //rotation speed
if (Gdx.input.isKeyPressed(Keys.LEFT))
rotateBy(degreesPerSecond * dt);
if (Gdx.input.isKeyPressed(Keys.RIGHT))
rotateBy(-degreesPerSecond * dt);
if (Gdx.input.isKeyPressed(Keys.UP)) {
accelerateAtAngle(getRotation());
thrusters.setVisible(true);
}
else {
thrusters.setVisible(false);
}
shield.setOpacity(shieldPower / 100f);
if (shieldPower <= 0)
shield.setVisible(false);
applyPhysics(dt);
wrapAroundWorld();
}
public void warp() {
if(getStage() == null)
return;
Warp warp1 = new Warp(0, 0, this.getStage());
warp1.centerAtActor(this);
setPosition(MathUtils.random(800),
MathUtils.random(600));
Warp warp2 = new Warp(0, 0, this.getStage());
warp2.centerAtActor(this);
}
public void shoot() {
if (getStage() == null)
return;
Laser laser = new Laser(0, 0, this.getStage());
laser.centerAtActor(this);
laser.setRotation(this.getRotation());
laser.setMotionAngle(this.getRotation());
}
}
The Laser class.
package com.mygdx.game;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
public class Laser extends BaseActor {
Rectangle bounds;
public Laser(float x, float y, Stage s) {
super(x, y, s);
bounds = new Rectangle((int)getX(), (int)getY(),
(int)getWidth(), (int)getHeight());
loadTexture("laser.png");
addAction(Actions.delay(1));
addAction(Actions.after(Actions.fadeOut(0.5f)));
addAction(Actions.after(Actions.removeActor()));
setSpeed(400);
setMaxSpeed(400);
setDeceleration(0);
}
public void act(float dt) {
super.act(dt);
applyPhysics(dt);
wrapAroundWorld();
}
public Rectangle getBounds() {
return bounds;
}
private void setXY(float pX,float pY) {
setPosition(pX, pY);
bounds.setX((int)pX);
bounds.setY((int)pY);
}
}
The Rock class
package com.mygdx.game;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.math.MathUtils;
import com.mygdx.game.BaseActor;
public class Rock extends BaseActor {
public boolean crashed;
Rectangle bounds;
public Rock(float x, float y, Stage s) {
super(x, y, s);
bounds = new Rectangle((int)getX(), (int)getY(),
(int)getWidth(), (int)getHeight());
loadTexture("rock.png");
float random = MathUtils.random(30);
addAction(Actions.forever(Actions.rotateBy(30 + random,
1)));
setSpeed(50 + random);
setMaxSpeed(50 + random);
setDeceleration(0);
setMotionAngle(MathUtils.random(360));
crashed = false;
}
public void act(float dt) {
super.act(dt);
applyPhysics(dt);
wrapAroundWorld();
}
public boolean isCrashed() {
return crashed;
}
public void crashed() {
crashed = true;
clearActions();
addAction(Actions.fadeOut(1));
addAction(Actions.after(Actions.removeActor()));
}
public Rectangle getBounds() {
return bounds;
}
private void setXY(float pX,float pY) {
setPosition(pX, pY);
bounds.setX((int)pX);
bounds.setY((int)pY);
}
}
Boundary and overlap methods from BaseActor class
public void setBoundaryPolygon(int numSides) {
float w = getWidth();
float h = getHeight();
float[] vertices = new float[2 * numSides];
for(int i = 0; i < numSides; i ++) {
float angle = i * 6.28f / numSides;
//x coordinate
vertices[2 * i] = w / 2 * MathUtils.cos(angle) + w / 2;
//y coordinate
vertices[2 * i + 1] = h / 2 * MathUtils.sin(angle) + h / 2;
}
boundaryPolygon = new Polygon(vertices);
}
public Polygon getBoundaryPolygon() {
boundaryPolygon.setPosition(getX(), getY());
boundaryPolygon.setOrigin(getOriginX(), getOriginY());
boundaryPolygon.setRotation(getRotation());
boundaryPolygon.setScale(getScaleX(), getScaleY());
return boundaryPolygon;
}
public boolean overlaps(BaseActor other) {
Polygon poly1 = this.getBoundaryPolygon();
Polygon poly2 = other.getBoundaryPolygon();
//initial text to improve performance
if(!poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()))
return false;
return Intersector.overlapConvexPolygons(poly1, poly2);
}
So I guess the real question would be how would I go about checking for collisions between the rocks ArrayList and the lasers fired by the player? At this point I just want to finish the game even if it's not using best practices. I tried using the method described here and received no errors but also no collision between lasers and rock. Even if I manually add a laser to the lasers ArrayList. This last post I found leads me to believe I need something like a getAllLasers() but I'm not 100% sure how to go about that. Would it be easier to just learn Box2D or Quadtree?
I realize this is a complex problem and want to thank you in advance for taking taking the time to read it. I'm happy to provide any more information you need.
You already have Rectangle bounds for both of this entities, this is all you need. You can use Rectangle.overlaps()
for(Laser laser: lasers){
for(Rock rock: rocks){
if(laser.getBounds().overlaps(rock.getBounds())){
//collided!
}
}
}
Make sure you are getting a updated rectangle/bounds. Add this extra line in both Rock and Laser getBounds() method:
public Rectangle getBounds() {
bounds.set(getX(),getY(),getWidth(),getHeight());
return bounds;
}
if your actors scales or rotate you should update bounds accordingly
I think problem may be with update your actors bounds, i can't find where you update it. I wrote similiar game and i change Bounds of actors on each update step and all works well in some lines...
public void update() {
...
// changing bounds
bounds = new Rectangle(position.x,position.y,
actorWidth,
actorHeight);
}
Or if you use other approach check that your bounds changing in time

Rotate image by x degrees? - Java [duplicate]

This question already has answers here:
Java: Rotating Images
(8 answers)
Closed 7 years ago.
All right, so I am attempting to create a simple-ish game and I have a galaxy swirly id like to rotate, only thing is though, I am unsure how, if I use the Graphics2D "g.rotate(x)" everything on screen I had drawn spins but I only want the galaxy to rotate and not the words and stuff.
Background class:
package TileMap;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Background {
private BufferedImage image;
private int x;
private int y;
private int dx;
private int dy;
public Background(String imgLctn){
try{
image = ImageIO.read(getClass().getResourceAsStream(imgLctn));
}
catch(Exception e){
e.printStackTrace();
}
}
public void draw(Graphics2D g){
g.drawImage(image, x - 44, y - 33, null);
}
}
The MainMenu class:
package GameState;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import Main.GamePanel;
import TileMap.Background;
public class MainMenu extends GameState {
private int currentChoice = 0;
private Background bg;
private String[] options = {
"Start",
"Options",
"Quit"
};
private Color titleColor;
private Font titleFont;
private Font subFont;
public MainMenu(GameStateManager gsm){
this.gsm = gsm;
try{
bg = new Background("/Backgrounds/MenuBG.png");
titleColor = new Color(0, 255, 0);
titleFont = new Font("Youre gone", Font.ITALIC, 30);
subFont = new Font("Youre gone", Font.PLAIN, 18);
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void init() {
}
#Override
public void update() {
}
#Override
public void draw(Graphics2D g) {
bg.draw(g);
g.setColor(titleColor);
g.setFont(titleFont);
g.drawString("On My Way To Mars", GamePanel.WIDTH1 / 8, GamePanel.HEIGHT1 / 3);
g.fillRect(GamePanel.WIDTH1 / 8, GamePanel.HEIGHT1 / 3, (int) (GamePanel.WIDTH1/1.53), 3);
for(int i = 0;i < options.length;i++){
g.setFont(subFont);
if(i == currentChoice){
g.setColor(new Color(255,0,255));
}
else{
g.setColor(new Color(0,255,255));
}
if(i < 1){
g.drawString(options[i], GamePanel.WIDTH1 / 8, GamePanel.HEIGHT1 / 2 + i);
}
else{
g.drawString(options[i], GamePanel.WIDTH1 / 8, (GamePanel.HEIGHT1 - 2) /2 + (i*20));
}
}
}
private void select(){
if(currentChoice == 0){
}
if(currentChoice == 1){
}
if(currentChoice == 2){
System.exit(0);
}
}
public void keyPressed(int k){
if(k == KeyEvent.VK_W){
System.exit(0);
}
}
}
I'm not an expert myself but this might help:
Java: Rotating Images
Here's their answer:
`// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;
// Rotation information
double rotationRequired = Math.toRadian(45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
Please note I'm not taking credit for the original posters code!!!

How to play music using libgdx

I have had trouble playing music using libgdx. My code is as follows:
package com.me.fixGame;
import java.util.Random;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
//import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Scaling;
import com.sun.jmx.snmp.tasks.Task;
public class fixGame implements ApplicationListener {
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture trash;
Texture paper;
SpriteBatch spritebatch;
Vector2 position;
Vector2 pas;
boolean collide;
boolean countMe=false;
Vector2 size;
Vector2 size2;
Vector2 pos;
Rectangle bounds;
float posSpeed=30;
Rectangle bounds2;
float delay = 1; // seconds
boolean counted= false;
int score = 3;
//Texture Gogreen;
String myScore;
Texture background;
CharSequence str = "Lives left: 3"; // = myScore;
CharSequence line = "Score: 0"; // = myScore;
String myLife;
int life=0;
BitmapFont font;
float x;
float y;
Sound sound;
boolean collision = false;
#Override
public void create() {
//Gogreen = new Texture(Gdx.files.internal("data/gogreenNow.jpg"));
background = new Texture(Gdx.files.internal("data/trash.png"));
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
sound = Gdx.audio.newSound(Gdx.files.internal("data/testjava.mp3"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
size2 = new Vector2(trash.getWidth() ,trash.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(paper.getWidth() ,paper.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, size2.x, size2.y);
}
#Override
public void dispose() {
}
public void update(){
bounds.set(pos.x, pos.y, size.x, size.y);
bounds2.set(position.x, position.y, size2.x, size2.y);
float pos1=Gdx.input.getAccelerometerX();
//if(pos1<0)
// pos1=(-1)*pos1;
position.x = position.x - 5*pos1;
}
#Override
public void render() {
sound.play(0.5f);
sound.dispose();
if(bounds.overlaps(bounds2)){
collision=true;
counted=true;
}else{
collision=false;
}
if(collision==true){
}
if(pos.y<640){
counted=false;
} else if(pos.y > 640 && collision==false && counted==false){
counted=true;
score= score-1;
myScore = "Lives left: " + score;
str = myScore;
}
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
if(position.x<0){
position.x= position.x+11;
}
if(position.x>425){
position.x= position.x-11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y=pos.y-posSpeed;
//posSpeed = posSpeed+(2/3);
if(pos.y<0){
pos.y = 700;
Random randomGenerator = new Random();
pos.x = randomGenerator.nextInt(500);
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
if (!collision) {
batch.draw(paper, pos.x, pos.y);
}
//batch.draw(paper, pos.x, pos.y);
batch.draw(trash, position.x, position.y);
font.setScale(3);
font.setColor(0.0f, 0.0f, 1.0f,1.0f);
font.draw(batch, str, 300,900);
font.draw(batch, line, 300, 950);
batch.end();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
My sound file I call over here:
sound = Gdx.audio.newSound(Gdx.files.internal("data/testjava.mp3"));
And the code I use to play it is:
sound.play();
sound.dispose();
For some reason it does not work on my desktop and my phone. I tested the the sound file actually had some sound in it.
You need to get rid of the sound.dispose(); call right after playing the sound, since it will dispose the sound file ;)
Just put it into your game's dispose(); method, so it will get removed after the game is done.
Also, you shouldn't call sound.play(0.5f); within your render-loop. Remember this function will get called about 60 times a second and you don't want to have the sound start 60 times a second.
So if it's some kind of sound effect that comes with a special event, like firing a bullet or hitting a target etc, just call sound.play(); one time, when you are actually firing the event.
https://github.com/libgdx/libgdx/wiki/Sound-effects
If you want to play background music, you should try streaming the music file. The wiki is awesome for that: https://github.com/libgdx/libgdx/wiki/Streaming-music
Hope it helps :)

How would I make a color Gradient with linear interpolation along with Linked list?

I am currently trying to make a rainbow trail that follows your mouse. i used Linkedlist to plot the points of my mouse so the trail follows along. The trail itself looks perfect its only the colors in the trail that don't look right. I'm wanting them to fade into each other. Someone told me to use linear interpolation and after looking into it for awhile it seems like it would work i just don't know how to implement it.
this is the code i have so far:
import impsoft.bots.ColorBot;
import impsoft.scripting.ibot.interfaces.AutoPaint;
import impsoft.scripting.types.ColorScript;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Deque;
import java.util.LinkedList;
import impsoft.scripting.ibot.structs.XY;
import impsoft.scripting.types.ColorSkeltonScriptable;
import impsoft.scripting.types.parallel.scriptjobs.ScriptJob;
public class MouseTrail extends ColorScript implements AutoPaint {
public MouseTrail(ColorBot c) {
super(c);
}
public void script() throws InterruptedException {
while(true) {
mt.setSize(500);
mt.exec();
sleep(100);
}
}
public static String name = "Mouse trail test";
public static String author = "Llaver";
public static String description = "test for mouse trail";
public static double version = 1.00;
public class MouseTrail2 extends ScriptJob implements AutoPaint {
private int size;
private final ColorSkeltonScriptable cs;
private final Deque<XY> trail = new LinkedList<XY>();
private final Color[] rainbow = new Color[]{
Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE, Color.magenta
};
public MouseTrail2(ColorSkeltonScriptable cs) {
super(cs);
this.cs = cs;
}
public void setSize(int s) {
size = s;
s = 200;
}
public void runV() {
try {
while (true) {
synchronized (trail) {
if (trail.size() >= size) {
trail.pop();
}
trail.offer(cs.getCurrentMouseXY());
}
sleep(1);
}
} catch (InterruptedException e) {
}
}
#Override
public void paint(Graphics g) {
final Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
synchronized (trail) {
float perc;
int idx;
for(int i = 1 ; i < trail.size() - 1 ; i++){
XY current = ((LinkedList<XY>) trail).get(i);
XY next = ((LinkedList<XY>) trail).get(i - 1);
perc = ((float)i / trail.size()) * 100f;
idx = Math.round((perc * (float)rainbow.length) / 100f);
if(idx >= rainbow.length)idx -= 1;
g2d.setColor(rainbow[idx]);
g.drawLine(current.x, current.y, next.x, next.y);
}
}
}
}
#Override
public void paint(Graphics arg0) {
}
private MouseTrail2 mt = new MouseTrail2(this);
}
some pics:
this is what i have right now:
http://img11.imageshack.us/img11/3031/mousetrailhavenow.png
this is what im trying to get:
http://img594.imageshack.us/img594/7381/mousetrailtryingtoget.png
does that possibly make this a little more clear?
To get the effect you want, you are probably going to have to create a custom gradient paint that spans the gamut of hue along one axis and the range of alpha transparency along the other. As a related example, this KineticModel uses a RadialGradientPaint to create an array of GradientImage instances. In each image, the alpha varies radially from 0xff (1.0) at the center to 0x3f (0.25) at the periphery.
Addendum: Based on your picture, just set the graphics context's Stroke to a suitable width, set the paint to the next hue from your color lookup table (clut), and drawLine(). You can vary the hue, keeping the the saturation and brightness constant.
float N = 360;
Queue<Color> clut = new LinkedList<Color>();
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor(i / N, 1, 1));
}
You'll have to decide when to change colors based on space or time. For the latter, javax.swing.Timer is a good choice.

Categories