Is this the right site to ask this question, since I've been referred to another site two times by now.
I'm trying to create bouncing balls with realistic physics. At the moment, when the balls hit each other, they bounce back in the same direction they were coming from, now, I've searched the internet for how to do this, but I only find things about how to detect collision, not what to do after. I don't know a lot about physics, are their topics I should learn first before I would be able to do this? Here's an image of how I imagine balls would bounce in real life. Is this how it works?
(source: thewombatguru.nl)
Also, do I have bad practises in my code? (probably, but I'm learning a lot and I like it)
This is my current code:
Asteroids.java
package Asteroids;
import javax.swing.*;
public class Asteroids {
public static void createAndShowGui() {
GamePanel gamePanel = new GamePanel();
JFrame frame = new JFrame("Asteroids");
frame.getContentPane().add(gamePanel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocation(2000, 50);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
GamePanel.java
package Asteroids;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class GamePanel extends JPanel implements ActionListener {
private final int WIDTH = 1000;
private final int HEIGHT = 1000;
Timer animationTimer;
ArrayList<Rock> rocks;
public GamePanel() {
Dimension preferredDimension = new Dimension(WIDTH, HEIGHT);
setPreferredSize(preferredDimension);
animationTimer = new Timer(10, this);
setUp();
}
public void setUp() {
rocks = new ArrayList<>();
rocks.add(new Rock(475, 1000, 0, -1));
rocks.add(new Rock(0, 500, 1, 0));
//rocks.add(new Rock(300, 270, -2, 2));
//rocks.add(new Rock(400, 315, -5, -1));
animationTimer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
for (Rock rock : rocks) {
for (Rock rockToCheck : rocks) {
if (!rock.equals(rockToCheck)) {
rock.checkForCollisionWithRocks(rockToCheck);
}
}
rock.checkForCollisionWithFrame(WIDTH, HEIGHT);
rock.setxPos(rock.getxPos() + rock.getxVelocity());
rock.setyPos(rock.getyPos() + rock.getyVelocity());
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
RenderingHints mainRenderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHints(mainRenderingHints);
for (Rock rock : rocks) {
rock.display(g2d);
}
g2d.dispose();
}
}
Rock.java
package Asteroids;
import java.awt.*;
public class Rock {
private int xPos;
private int yPos;
private int rockWidth;
private int rockHeight;
private int xVelocity;
private int yVelocity;
private int rockRadius;
private Color rockColor;
public Rock(int xPos, int yPos, int xVelocity, int yVelocity) {
this.xPos = xPos;
this.yPos = yPos;
this.xVelocity = xVelocity;
this.yVelocity = yVelocity;
rockWidth = 50;
rockHeight = rockWidth;
rockRadius = rockWidth / 2;
rockColor = new Color((int) (Math.random() * 255),(int) (Math.random() * 255),(int) (Math.random() * 255));
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getxPos() {
return xPos;
}
public int getRockWidth() {
return rockWidth;
}
public void setRockWidth(int rockWidth) {
this.rockWidth = rockWidth;
}
public int getRockHeight() {
return rockHeight;
}
public void setRockHeight(int rockHeight) {
this.rockHeight = rockHeight;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
public int getxVelocity() {
return xVelocity;
}
public void setxVelocity(int xVelocity) {
this.xVelocity = xVelocity;
}
public int getyVelocity() {
return yVelocity;
}
public void setyVelocity(int yVelocity) {
this.yVelocity = yVelocity;
}
public int getRockRadius() {
return rockRadius;
}
public void setRockRadius(int rockRadius) {
this.rockRadius = rockRadius;
}
public void checkForCollisionWithRocks(Rock rock) {
int radiusOfBoth = rock.getRockRadius() + rockRadius;
int horDistance = Math.abs((rock.getxPos() + rock.getRockRadius()) - (xPos + rockRadius));
int verDistance = Math.abs((rock.getyPos() + rock.getRockRadius()) - (yPos + rockRadius));
int diagDistance = (int) Math.sqrt(Math.pow(horDistance, 2) + Math.pow(verDistance, 2));
if (diagDistance <= radiusOfBoth) {
xVelocity = -xVelocity;
yVelocity = -yVelocity;
rock.setxVelocity(-rock.getxVelocity());
rock.setyVelocity(-rock.getyVelocity());
rock.setxPos(rock.getxPos() + rock.getxVelocity());
rock.setyPos(rock.getyPos() + rock.getyVelocity());
}
}
public void checkForCollisionWithFrame(final int WIDTH, final int HEIGHT) {
if (xPos < 0) {
xVelocity *= -1;
xPos = 0;
} else if (xPos + rockWidth > WIDTH) {
xVelocity *= -1;
xPos = WIDTH - rockWidth;
}
if (yPos < 0) {
yVelocity *= -1;
yPos = 0;
} else if (yPos + rockHeight > HEIGHT) {
yVelocity *= -1;
yPos = HEIGHT - rockHeight;
}
}
public void display(Graphics2D g2d) {
g2d.setColor(rockColor);
g2d.fillOval(xPos, yPos, rockWidth, rockHeight);
}
}
Can anyone help ?
You can start with the law of conservation of momentum. When two objects collide the total momentum will not change, you can use this link to understand the calculations behind while trying to predict the trajectories of two objects after they collide.
As for your code, you seem to be missing a crucial field mass in your Rock.java. You need mass in order to calculate the momentum of an object which later you will use to predict the trajectories after the objects collide.
EDIT: Note that the examples in the link are somewhat limited to 2 directions where the objects collide against each other with 180* between them. However it is not that hard to generalize and find the velocity of an object after the collision by breaking down the momentum/velocity vectors to 4 directions, that are 0,90,180,270 degrees. You have to use vector math to express the speed of a given object in terms of the 4 directions.
Real life physics is tricky (gravity, inertia, etc), but to start with, bouncing the balls off of each other:
When the two balls hit, there's an angle of collision. Luckily, because they are circles (assuming) you can find the angle of incidence by finding the angle of the line going through the center of the two balls. Then you want to send 1 ball off 1 way perpendicular the that line, and the other the other way.
Make sense?
Answer here:
Also there is a nice gif,you can easily find out,how to calculate the new velocities ;)
Ball to Ball Collision - Detection and Handling
Related
I have an assignment to create a 2D game, this game must use an abstract class Shape which is used to draw shapes. I decided to make a 2D platformer, but it's my first time doing something like this. I am trying to implement collision detection, and decided to create an offset of my player object to see if it collides with my rectangle object, and stop movement if it does. This is only working for the top side, however on the right, left and botton the player will move through the rectangle and I don't understand why. I expected the collision detection to work for all sides. I would like to know how I can change my collision detection to work for all sides of the rectangle.
Here's a gif showing what happens:
My App class:
package A2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.TreeSet;
import static java.awt.event.KeyEvent.*;
public class App extends JFrame {
private static final int GRAVITY = 10;
private static final int MAX_FALL_SPEED = 30;
public App() {
final Player player = new Player(200, 300);
final Rectangle rectangle = new Rectangle(100, 400);
JPanel mainPanel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
player.draw(g);
rectangle.draw(g);
}
};
mainPanel.addKeyListener(new controlHandler(this, player, rectangle));
mainPanel.setFocusable(true);
add(mainPanel);
setLayout(new GridLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(600, 600);
}
class controlHandler implements ActionListener, KeyListener {
int keyCode;
App app;
Player player;
Rectangle rectangle;
TreeSet<Integer> keys = new TreeSet<>();
Timer time = new Timer(5, this);
boolean collision = false;
public controlHandler(App app, Player player, Rectangle rectangle) {
this.app = app;
this.player = player;
this.rectangle = rectangle;
time.start();
}
public void actionPerformed(ActionEvent e) {
player.x += player.xVelocity;
player.y += player.yVelocity;
Rectangle2D offset = player.getOffsetBounds();
if(offset.intersects(this.rectangle.wallObj.getBounds2D())){
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
}
else collision = false;
repaint();
}
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
keys.add(keyCode);
switch (keyCode) {
case VK_UP:
moveUp();
break;
case VK_DOWN:
moveDown();
break;
case VK_LEFT:
moveLeft();
break;
case VK_RIGHT:
moveRight();
break;
}
}
public void keyReleased(KeyEvent e) {
released();
}
public void keyTyped(KeyEvent e) { }
public void moveUp() {
player.xVelocity = 0;
player.yVelocity = -2;
}
public void moveDown() {
if(!collision) {
player.xVelocity = 0;
player.yVelocity = 2;
}
}
public void moveLeft() {
player.xVelocity = -2;
player.yVelocity = 0;
}
public void moveRight() {
player.xVelocity = 2;
player.yVelocity = 0;
}
public void released() {
player.xVelocity = 0;
player.yVelocity = 0;
}
}
public static void main(String[] args) {
App app = new App();
app.setVisible(true);
}
}
abstract class Shape {
public double x;
public double y;
public void draw(Graphics g) { }
}
Player class:
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Player extends Shape {
public double xVelocity;
public double yVelocity;
public double length = 60;
public double top;
public double right;
public double left;
public double bottom;
public Rectangle2D playerObj;
public Player(double x, double y) {
this.x = x;
this.y = y;
playerObj = new Rectangle2D.Double(x, y, length, length);
}
public Rectangle2D getOffsetBounds(){
return new Rectangle2D.Double(x + xVelocity , y + yVelocity , length, length);
}
public void draw(Graphics g) {
playerObj = new Rectangle2D.Double(x, y, length, length);
g.setColor(Color.BLACK);
Graphics2D g2 = (Graphics2D)g;
g2.fill(playerObj);
}
}
Rectangle class (will be a platform):
package A2;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class Rectangle extends Shape {
public double width = 400;
public double height = 30;
public double top;
public double right;
public double left;
public double bottom;
public Rectangle2D wallObj;
public Rectangle(double x, double y) {
this.x = x;
this.y = y;
wallObj = new Rectangle2D.Double(x, y, width, height);
}
public void draw(Graphics g) {
g.setColor(Color.ORANGE);
Graphics2D g2 = (Graphics2D)g;
g2.fill(wallObj);
}
}
So, based on my understanding, your collision detection process is basically to create a "virtual" instance of the object and determine if it will collide.
Your code is actually work, you can tell by the fact that the object "stops" moving once it collides, but what you're not doing, is reseting the objects position after it.
Let's look at the original code...
public void actionPerformed(ActionEvent e) {
player.x += player.xVelocity;
player.y += player.yVelocity;
Rectangle2D offset = player.getOffsetBounds();
if (offset.intersects(this.rectangle.wallObj.getBounds2D())) {
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
} else {
collision = false;
}
repaint();
}
Update the position of the object
Create a virtual instance of the object, which applies the velocity to the objects current position ... again?
Determine if the object collides
Stop the movement if any
... where do you reset the position of object so it's no longer colliding?!?
Instead, you shouldn't set the position of the object until AFTER you've determine if a collision has occurred or not, for example...
public void actionPerformed(ActionEvent e) {
Rectangle2D offset = player.getOffsetBounds();
if (offset.intersects(this.rectangle.wallObj.getBounds2D())) {
collision = true;
player.xVelocity = 0;
player.yVelocity = 0;
} else {
player.x += player.xVelocity;
player.y += player.yVelocity;
collision = false;
}
repaint();
}
The problem with this approach, though, is if the velocity is large enough, the object will appear not to collide, but stop a little before it, as the amount of change is larger than the remaining gap.
What you need to do, is once you've detected a collision is calculate the difference between the amount you want to move and the space available and move the object only by that amount instead
I'm trying to draw isometric tiles in Java and implement a tile picking system using the mouse cursor. I draw the tiles using these math formulas I found and adapted to my tile textures which you can find below. Tiles are 64x64px but flat tiles are only 32px height even if I draw them using the 64x64 sprite.
The map is a simple 2d array where my tiles are represented by their id.
Here is the class I use to convert map coordinates to screen coordinates using the toIso() function. I pass my screen coordinates which represent the cursor position on the screen to the toGrid() function to convert them to map coordinates.
public class Utils {
private static int TILE_WIDTH = Tile.TILE_WIDTH;
private static int TILE_HEIGHT = Tile.TILE_HEIGHT;
private static int TILE_WIDTH_HALF = TILE_WIDTH/2;
private static int TILE_HEIGHT_HALF = TILE_HEIGHT/2;
private static int TILE_WIDTH_QUARTER = TILE_WIDTH_HALF/2;
private static int TILE_HEIGHT_QUARTER = TILE_HEIGHT_HALF/2;
public static int[] toIso(int x, int y){
int i = (x - y) * TILE_WIDTH_HALF;
int j = (x + y) * TILE_HEIGHT_QUARTER;
//800 and 100 are temporary offsets I apply to center the map.
i+=800;
j+=100;
return new int[]{i,j};
}
public static int[] toGrid(int x, int y){
//800 and 100 are temporary offsets I apply to center the map.
x-=800;
y-=100;
int i = ( x / ( TILE_WIDTH_HALF ) + y / ( TILE_HEIGHT_QUARTER )) / 2;
int j = ( y / ( TILE_HEIGHT_QUARTER ) - ( x / ( TILE_WIDTH_HALF ))) / 2;
return new int[]{i,j};
}}
I currently render my tiles by using two for loops and converting the map coordinates to screen coordinates using the toIso() function.
public void render(Graphics g){
for(int x = 0;x<width;x++){
for(int y = 0;y<height;y++){
int[] isoCoords = Utils.toIso(x, y);
int fx = isoCoords[0];//
int fy = isoCoords[1];//
if(world[x][y] == 0){
Tile grass = new GrassTile(0);
grass.render(g, grass.getId(), fx, fy);
}else if(world[x][y] == 1){
Tile water = new WaterTile(1);
water.render(g, water.getId(), fx, fy);
}
}
}
}
I get a diamond shape as I wanted rendered on the screen.
I finally update each tick which are the actual mouse coordinates on screen.
int[] coords = Utils.toGrid(mouseManager.getMouseX(), mouseManager.getMouseY());
tileX = coords[0];
tileY = coords[1];
The selected tile is finally rendered:
BufferedImage selectedTexture = Assets.selected;
int[] coordsIsoSelected = Utils.toIso(this.tileX, this.tileY);
g.drawImage(selectedTexture, coordsIsoSelected[0], coordsIsoSelected[1], Tile.TILE_WIDTH, Tile.TILE_HEIGHT, null);
g.drawRect(Utils.toIso(tileX, tileY)[0], Utils.toIso(tileX, tileY)[1]+Tile.TILE_HEIGHT/2, Tile.TILE_WIDTH, Tile.TILE_HEIGHT/2);//I draw a rectangle to visualize what's happening.
Finally, my tile detection isn't working as expected, it isn't fitting the tiles perfectly, however it seems to be in relation with the rectangle I draw. I can't figure out the solution to this problem, I thank you in advance for reading or any advice you could give to me. If you need more precisions, I would be glad to give you more informations.
Here is a video showing what is actually happening: youtu.be/baCVIfJz2Wo
EDIT:
Here is some of my code you could use to run an application like mine. Sorry for this very messy code, but I tried to make it as short as possible without disturbing the behavior of the "game".
You will need to put the sheet provided before into a "textures" folder created into the ressource folder of the project.
The gfx package:
package fr.romainimberti.isometric.gfx;
import java.awt.image.BufferedImage;
public class Assets {
private static final int width = 64, height = 64;
public static BufferedImage grass, water, selected;
public static void init(){
//Temp
SpriteSheet tileSheet = new SpriteSheet(ImageLoader.loadImage("/textures/sheet.png"));
grass = tileSheet.crop(width*2, 0, width, height);
water = tileSheet.crop(width*9, height*5, width, height);
selected = tileSheet.crop(0, height*5, width, height);
//
}
}
package fr.romainimberti.isometric.gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageLoader {
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
}
package fr.romainimberti.isometric.gfx;
import java.awt.image.BufferedImage;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(BufferedImage sheet){
this.sheet = sheet;
}
public BufferedImage crop(int x, int y, int width, int height){
return sheet.getSubimage(x, y, width, height);
}
}
The rest of the project:
package fr.romainimberti.isometric;
public class Launcher {
public static void main(String args[]){
System.setProperty("sun.awt.noerasebackground", "true");
Game game = new Game("Isometric", 1280, 720);
game.start();
}
}
package fr.romainimberti.isometric;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Display {
private JFrame frame;
private Canvas canvas;
private String title;
private int width, height;
public Display(String title, int width, int height){
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(true);
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas(){
return canvas;
}
public JFrame getFrame(){
return frame;
}
}
package fr.romainimberti.isometric;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.concurrent.ThreadLocalRandom;
import javax.swing.JFrame;
import fr.romainimberti.isometric.gfx.Assets;
public class Game implements Runnable {
private Display display;
private int width, height;
public JFrame frame;
private boolean running = false;
private Thread thread;
public String title;
private BufferStrategy bs;
private Graphics g;
public int x, y;
public int[][] world;
public static final int TILE_WIDTH = 64;
public static final int TILE_HEIGHT = 64;
public static final int TILE_WIDTH_HALF = 32;
public static final int TILE_HEIGHT_HALF = 32;
public static final int TILE_WIDTH_QUARTER = 16;
public static final int TILE_HEIGHT_QUARTER = 16;
public int xOffset;
//Input
private MouseManager mouseManager;
public Game(String title, int width, int height){
this.width = width;
this.height = height;
this.mouseManager = new MouseManager(this);
this.world = new int[10][10];
}
private void init(){
display = new Display(title, width, height);
display.getFrame().addMouseListener(mouseManager);
display.getFrame().addMouseMotionListener(mouseManager);
display.getCanvas().addMouseListener(mouseManager);
display.getCanvas().addMouseMotionListener(mouseManager);
this.frame = display.getFrame();
Assets.init();
xOffset = frame.getWidth()/2;
//Fill the world
for(int i = 0;i<world.length;i++){
for(int j=0;j<world[0].length;j++){
int r = ThreadLocalRandom.current().nextInt(0,1+1);
if(r == 0)
world[i][j] = 0;
else
world[i][j] = 1;
}
}
}
private void tick(){
mouseManager.tick();
xOffset = frame.getWidth()/2;
}
private void render(){
bs = display.getCanvas().getBufferStrategy();
if(bs == null){
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, frame.getWidth(), frame.getHeight());
//Draw Here
//World render
for(int x = 0;x<world.length;x++){
for(int y = 0;y<world[0].length;y++){
int[] isoCoords = toIso(x, y);
int fx = isoCoords[0];//
int fy = isoCoords[1];//
if(world[x][y] == 0){
g.drawImage(Assets.grass, fx, fy, null);
}else if(world[x][y] == 1){
g.drawImage(Assets.water, fx, fy, null);
}
}
}
//Selected tile render
int[] coordsIsoSelected = toIso(x, y);
g.drawImage(Assets.selected, coordsIsoSelected[0], coordsIsoSelected[1], TILE_WIDTH, TILE_HEIGHT, null);
//End Drawing
bs.show();
g.dispose();
}
public void run(){
init();
int fps = 120;
double timePerTick = 1000000000 / fps;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while(running){
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
lastTime = now;
if(delta >= 1){
tick();
render();
delta--;
}
}
stop();
}
public MouseManager getMouseManager(){
return mouseManager;
}
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop(){
if(!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static int[] toIso(int x, int y){
int i = (x - y) * TILE_WIDTH_HALF;
int j = (x + y) * TILE_HEIGHT_QUARTER;
i+=xOffset;
return new int[]{i,j};
}
public static int[] toGrid(int x, int y){
x-=xOffset;
int i = ( x / ( TILE_WIDTH_HALF ) + y / ( TILE_HEIGHT_QUARTER )) / 2;
int j = ( y / ( TILE_HEIGHT_QUARTER ) - ( x / ( TILE_WIDTH_HALF ))) / 2;
return new int[]{i,j};
}
}
package fr.romainimberti.isometric;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class MouseManager implements MouseListener, MouseMotionListener {
private boolean leftPressed, rightPressed;
private int mouseX, mouseY;
private Game game;
public MouseManager(Game game){
this.game = game;
}
public void tick(){
game.x = game.toGrid(mouseX, mouseY)[0];
game.y = game.toGrid(mouseX, mouseY)[1];
}
// Getters
public boolean isLeftPressed(){
return leftPressed;
}
public boolean isRightPressed(){
return rightPressed;
}
public int getMouseX(){
return mouseX;
}
public int getMouseY(){
return mouseY;
}
// Implemented methods
#Override
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1)
leftPressed = true;
else if(e.getButton() == MouseEvent.BUTTON3)
rightPressed = true;
}
#Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1)
leftPressed = false;
else if(e.getButton() == MouseEvent.BUTTON3)
rightPressed = false;
}
#Override
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
If you need it, you can find here my project architecture so you can organize all the files correctly.
Again, sorry for this very, very messy code but I had to split all the usefull parts of my game to reduce it's size. Also don't forget to download and place correctly the sheet file. Hope this will help.
128*64 tiles
just wanted to say that I finally solved it. It was just a conversion to int issue. These are the final methods that I use. Hope it will help people who are trying to work with isometric tiles. Thank you !
public static int[] toIso(int x, int y){
int i = (x - y) * TILE_WIDTH_HALF;
int j = (x + y) * TILE_HEIGHT_QUARTER;
i += xOffset-TILE_WIDTH_HALF;
j+=yOffset;
return new int[]{i,j};
}
public static int[] toGrid(double i, double j){
i-=xOffset;
j-=yOffset;
double tx = Math.ceil(((i / TILE_WIDTH_HALF) + (j / TILE_HEIGHT_QUARTER))/2);
double ty = Math.ceil(((j / TILE_HEIGHT_QUARTER) - (i / TILE_WIDTH_HALF))/2);
int x = (int) Math.ceil(tx)-1;
int y = (int) Math.ceil(ty)-1;
return new int[]{x, y};
}
After replacing the spritesheet with the new one with 128x64 pixels' tiles, I've been able to achieve the desired output partially...
Why I say "partially"? Because I've managed to get the desired result only from the half right part of the map.
I believe it could have something to do with how the map is being painted, I'm not a native English speaker so I might be misunderstanding what the "Notes" section says in OP's link:
Notice that the "origin" of the isometric tile is the top corner. But usually when we draw a sprite it's from the top-left corner
I've called the methods toGrid() and toIso() at the beginning of the program as follows:
int[] coordinates = Game.toIso(2, 1);
System.out.println(coordinates[0] + "-" + coordinates[1]);
int[] coordinates2 = Game.toGrid(coordinates[0], coordinates[1]);
System.out.println(coordinates2[0] + "-" + coordinates2[1]);
And got the following results, (Which indeed are what we were expecting), so we know the methods work correctly:
64-96
2-1
I was sure to modify the Assets file:
public static final int WIDTH = 128, HEIGHT = 64;
Where I also changed the variable names following the Java naming conventions (ALL_WORDS_UPPER_CASE_CONSTANTS) and made it public instead of private
I also changed the Game file:
public static final int TILE_WIDTH = Assets.WIDTH;
public static final int TILE_HEIGHT = Assets.HEIGHT;
public static final int TILE_WIDTH_HALF = TILE_WIDTH / 2;
public static final int TILE_HEIGHT_HALF = TILE_HEIGHT / 2;
public static final int TILE_WIDTH_QUARTER = TILE_WIDTH / 4;
public static final int TILE_HEIGHT_QUARTER = TILE_HEIGHT / 4;
To use those constants on the Assets file and calculate the HALF and QUARTER instead of hardcoding it.
I also believe xOffset shouldn't be public but private as well as some other variables on the program...
The tick() method, doesn't need to calculate the xOffset everytime, so we can get rid of this line inside it:
xOffset = frame.getWidth() / 2 - 65;
I also changed the way you paint the tile you're selecting as:
// Selected tile render
int[] coordsIsoSelected = toIso(x, y);
g.drawImage(Assets.selected, coordsIsoSelected[0], coordsIsoSelected[1], TILE_WIDTH, TILE_HEIGHT, null);
And for the Tolso equations, I changed them to:
public static int[] toIso(int x, int y) {
int i = (x - y) * TILE_WIDTH_HALF;
int j = (x + y) * TILE_HEIGHT_HALF;
i += xOffset;
return new int[] { i, j };
}
Below I adjusted the parenthesis locations:
public static int[] toGrid(int x, int y) {
x -= xOffset;
int i = ((x / TILE_WIDTH_HALF) + (y / TILE_HEIGHT_HALF)) / 2;
int j = ((y / TILE_HEIGHT_HALF) - (x / TILE_WIDTH_HALF)) / 2;
return new int[] { i, j };
}
I want to create a method that creates 5 balls on a panel. Can somebody please help me get around this using the paint component method or creating my own draw method. As you can see bellow, i have a paint component method with a for loop that will loop 5 and create a ball in a random location, but unfortunately only one ball is being created.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class AllBalls extends JPanel {
int Number_Ball=5;
int x,y;
Graphics g;
AllBalls(){
Random r = new Random();
x=r.nextInt(320);
y=r.nextInt(550);
}
public static JFrame frame;
public static void main(String[] args) {
AllBalls a= new AllBalls();
frame= new JFrame("Bouncing Balls");
frame.setSize(400,600);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(a);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=0;i<Number_Ball;i++){
g.fillOval(x, y, 30, 30);
}
repaint();
}
}
In my paintComponent method, i created a for loop in which i wanted 5 ball to be created, but only one is being created on the screen.
Recommendations as per my comments:
Get rid of the Graphics g variable as that will only hurt you.
Consider creating a non-GUI Ball class, one that does not extend any Swing component and has its own paint(Graphics) method.
If you need 5 balls, create an array of Ball objects in your AllBalls class.
In paintComponent, iterate through the Balls painting each one by calling its paint or draw method (whatever you name the method).
If you need to move the balls, do so in a Swing Timer that moves the balls and then calls repaint(). Whatever you do, do not call repaint() within the paintComponent method as this results in a bastardization of the method, and results in a completely uncontrolled animation. This method should be for painting and painting only and not for animation or code logic. Use the Swing Timer instead.
Also don't randomize your ball locations within paintComponent, another recommendation made in a now-deleted answer. Again, paintComponent should be for painting and painting only and not for program logic or to change the state of your class. The randomization should be within your Swing Timer or game loop.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings({"serial", "unused"})
public class BallImages extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = PREF_W;
private static final int BALL_COUNT = 15;
private static final Color[] COLORS = { Color.RED, Color.BLACK, Color.BLUE,
Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK, Color.WHITE,
Color.MAGENTA, Color.YELLOW };
private static final int MIN_SPEED = 2;
private static final int MAX_SPEED = 10;
private static final int MIN_WIDTH = 10;
private static final int MAX_WIDTH = 30;
private static final int TIMER_DELAY = 15;
private List<Ball> balls = new ArrayList<>();
private Random random = new Random();
public BallImages() {
for (int i = 0; i < BALL_COUNT; i++) {
int ballWidth = MIN_WIDTH + random.nextInt(MAX_WIDTH - MIN_WIDTH);
Color ballColor = COLORS[random.nextInt(COLORS.length)];
int ballX = ballWidth / 2 + random.nextInt(PREF_W - ballWidth / 2);
int ballY = ballWidth / 2 + random.nextInt(PREF_H - ballWidth / 2);
double direction = 2 * Math.PI * Math.random();
double speed = MIN_SPEED + random.nextInt(MAX_SPEED - MIN_SPEED);
Ball ball = new Ball(ballWidth, ballColor, ballX, ballY, direction,
speed);
balls.add(ball);
}
new Timer(TIMER_DELAY, new TimerListener()).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Ball ball : balls) {
ball.draw(g2);
}
}
#Override
// set the component's size in a safe way
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (!BallImages.this.isDisplayable()) {
((Timer) e.getSource()).stop();
}
for (Ball ball : balls) {
ball.move(PREF_W, PREF_H);
}
repaint();
}
}
private class Ball {
private int width;
private Color color;
private double x;
private double y;
private double direction;
private double speed;
private double deltaX;
private double deltaY;
public Ball(int width, Color color, int x, int y, double direction,
double speed) {
this.width = width;
this.color = color;
this.x = x;
this.y = y;
this.direction = direction;
this.speed = speed;
deltaX = speed * Math.cos(direction);
deltaY = speed * Math.sin(direction);
}
public int getWidth() {
return width;
}
public Color getColor() {
return color;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getDirection() {
return direction;
}
public double getSpeed() {
return speed;
}
public void draw(Graphics2D g2) {
g2.setColor(color);
int x2 = (int) (x - width / 2);
int y2 = (int) (y - width / 2);
g2.fillOval(x2, y2, width, width);
}
public void move(int containerWidth, int containerHeight) {
double newX = x + deltaX;
double newY = y + deltaY;
if (newX - width / 2 < 0) {
deltaX = Math.abs(deltaX);
newX = x + deltaX;
}
if (newY - width / 2 < 0) {
deltaY = Math.abs(deltaY);
newY = y + deltaY;
}
if (newX + width / 2 > containerWidth) {
deltaX = -Math.abs(deltaX);
newX = x + deltaX;
}
if (newY + width / 2 > containerHeight) {
deltaY = -Math.abs(deltaY);
newY = y + deltaY;
}
x = newX;
y = newY;
}
}
private static void createAndShowGui() {
BallImages mainPanel = new BallImages();
JFrame frame = new JFrame("BallImages");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm having trouble getting my bullets to go where they want and I was hoping I could get some help identifying where my calculations are off.
Basically I'm making a 2d game and where ever you click on the screen a bullet should shoot at that location that you clicked, but the problem is that my bullets are not going where I want them to. Now I believe my problem is somewhere in the checkScreenForTouch() method and how I'm calculating what should be added to the bullets location. I'm not the best at trigonometry but I do understand it, so if any one has any advice on how to fix the following code that would be super cool :).
private void updateBullets(float dt){
batch.begin();
for(int i = 0; i < bullets.size(); i++){
Bullet b = bullets.get(i);
b.velocity.x += b.deltaX * b.speed;
b.velocity.y += b.deltaY * b.speed;
b.position.x += b.velocity.x * dt;
b.position.y += b.velocity.y * dt;
batch.draw(bullTex, b.position.x, b.position.y, bullTex.getWidth(), bullTex.getHeight());
if(b.position.x < 0 || b.position.x > sWidth || b.position.y < 0 || b.position.y > sHeight){
bullets.remove(b);
continue;
}
}
batch.end();
}
private void checkForScreenTouch(float dt){
if(Gdx.input.isTouched()){
Bullet b = new Bullet();
double angle = Math.atan((p.pos.y - Gdx.input.getY())/(p.pos.x - Gdx.input.getX()));
b.deltaX = Math.cos(angle);
b.deltaY = Math.sin(angle);
b.position.x = p.pos.x; //sets bullet start position equal to the players
b.position.y = p.pos.y;
bullets.add(b); // array list of bullets
}
}
If you need anything clarified just let me know. Thanks.
I see you still haven't really gotten any advice on this. Had some time, so I thought I'd whip something up.
The problems you were having I was able to reproduce by using your code.
Bullets only shoot to the right - This was solved by using atan2(dy, dx).
Opposite angle of what they are supposed to be - This was caused because the calculation p.pos.y - Gdx.input.getY() should really have been negated: Gdx.input.getY() - p.pos.y. Just a simple mix up. When the mouse has a larger y coordinate than the player location, you'd want the change in y to be positive.
Notes about the application:
Some issue with frame resizing. Tends to crop out bullets mid-trajectory.
I divide the change in time by 1000 to signify I want the velocity to be of pixels/second. Just a habit thing from physics 20.
The application is in swing. The code you will really want is within the makeProjectile function at the top.
Beyond that, I just used a synchronized list to avoid concurrency issues with the updates and the rendering.
If you have any questions, feel free to ask :)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
/**
* #author Obicere
*/
public class ProjectileTest {
// It's dangerous to go alone! Take this.
public void makeProjectile(final MouseEvent e, final int width, final int height){
final int x = width / 2;
final int y = height / 2;
final double angle = Math.atan2(e.getY() - y, e.getX() - x);
final double deltaX = Math.cos(angle);
final double deltaY = Math.sin(angle);
projectiles.add(new Projectile(x, y, deltaX, deltaY));
}
private static final double PROJECTILE_VELOCITY = 100; // Pixels per second
private final Collection<Projectile> projectiles = Collections.synchronizedCollection(new LinkedList<>());
public static void main(final String[] args){
SwingUtilities.invokeLater(ProjectileTest::new);
}
public ProjectileTest(){
final JFrame frame = new JFrame("Projectile Test");
final JPanel content = new JPanel(){
private final Dimension size = new Dimension(500, 500);
#Override
public void paintComponent(final Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawOval(getWidth() / 2 - 2, getHeight() / 2 - 2, 4, 4);
projectiles.forEach((e) -> e.render(g));
}
#Override
public Dimension getPreferredSize(){
return size;
}
};
content.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(final MouseEvent e) {
makeProjectile(e, content.getWidth(), content.getHeight());
}
});
content.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(final MouseEvent e) {
makeProjectile(e, content.getWidth(), content.getHeight());
}
});
final Timer repaint = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final Iterator<Projectile> iter = projectiles.iterator();
while(iter.hasNext()){
final Projectile next = iter.next();
if(!next.valid()){
iter.remove();
}
next.step(content.getWidth(), content.getHeight());
}
frame.repaint();
}
});
frame.add(content);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
repaint.start();
}
public class Projectile {
private final double velocityX;
private final double velocityY;
private double x;
private double y;
private long lastUpdate;
private boolean valid = true;
public Projectile(final double x, final double y, final double vx, final double vy){
this.x = x;
this.y = y;
this.velocityX = vx;
this.velocityY = vy;
this.lastUpdate = System.currentTimeMillis();
}
public boolean valid(){
return valid;
}
public void destroy(){
this.valid = false;
}
public void step(final int width, final int height){
final long time = System.currentTimeMillis();
final long change = time - lastUpdate;
this.x += (change / 1000D) * (velocityX * PROJECTILE_VELOCITY);
this.y += (change / 1000D) * (velocityY * PROJECTILE_VELOCITY);
this.lastUpdate = time;
if(x < 0 || y < 0 || x > width || y > height){
destroy();
}
}
public void render(final Graphics g){
g.setColor(Color.RED);
g.drawOval((int) x - 2, (int) y - 2, 4, 4);
}
}
}
This is a grade 12 object oriented programming project.
I have a class called Ball to construct my ball object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Ball{
private double xPos;
private double yPos;
private int direction;
public Ball(int ixPos, int iyPos, int idirection){
xPos = ixPos;
yPos = iyPos;
direction = idirection;
}
public int returnX(){
return (int)xPos;
}
public int returnY(){
return (int)yPos;
}
public int returnDirection(){
return direction;
}
public void move(){
xPos += 1*Math.cos(Math.toRadians(direction));
yPos -= 1*Math.sin(Math.toRadians(direction));
}
public void collide(int collideWith){
if(collideWith==1){//collide with left wall
if(90<direction && direction<180){
direction = 180-direction;
}
if(180<direction && direction<270){
direction = 540-direction;
}
}
if(collideWith==2){//collide with right wall
if(0<direction && direction<90){
direction = 180-direction;
}
if(270<direction && direction<360){
direction = 540-direction;
}
}
if(collideWith==3){//collide with up wall
if(0<direction && direction<90){
direction = 360-direction;
}
if(90<direction && direction<180){
direction = 360-direction;
}
}
if(collideWith==4){//collide with down wall
direction = 360-direction;
}
}
public void collidePaddle(int collidePos){
if(collidePos!=50 && collidePos!=0){
direction = (50-collidePos)*180/50;
}
}
}
As you can see in the "move" function, right now the ball is going at a very low speed. But i need the ball to go faster. If I change the 1 into something like, 5, there would be a problem. In my main class where it checks if the ball is hitting the wall or blocks to change direction, the ball would go into the wall or the blocks if the amount of pixels the ball can move each time is greater than 1.
To me it seems like there's no way to solve this problem, no idea where I would start thinking, is there a better way of checking collide or something?
Thank you.
Instead of using absolute checks in your collidePaddle check, you should allow for ranges.
For example...
public void collidePaddle(int collidePos){
if (collidePos >= 50) {
direction = (50-collidePos)*180/50;
// Correct the position of the ball to meet the minimum requirements
// of the collision...
} else if (collidePos <= 0) {
direction = (50-collidePos)*180/50;
// Correct the position of the ball to meet the minimum requirements
// of the collision...
}
}
(Sorry, I'm having fun working out your code ;))
This will allow the ball the "pass" beyond the these points within a virtual context, but if you correct the position to componsate, it should make no difference...when it's rendered...
Updated
Here's a REALLY SIMPLE example of what I'm talking about...
public class SimpleBouncyBall {
public static void main(String[] args) {
new SimpleBouncyBall();
}
public SimpleBouncyBall() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CourtPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class CourtPane extends JPanel {
private Ball ball;
private int speed = 5;
public CourtPane() {
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Rectangle bounds = new Rectangle(new Point(0, 0), getSize());
if (ball == null) {
ball = new Ball(bounds);
}
speed = ball.move(speed, bounds);
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (ball != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Point p = ball.getPoint();
g2d.translate(p.x, p.y);
ball.paint(g2d);
g2d.dispose();
}
}
}
public class Ball {
private Point p;
private int radius = 12;
public Ball(Rectangle bounds) {
p = new Point();
p.x = 0;
p.y = bounds.y + (bounds.height - radius) / 2;
}
public Point getPoint() {
return p;
}
public int move(int speed, Rectangle bounds) {
p.x += speed;
if (p.x + radius >= (bounds.x + bounds.width)) {
speed *= -1;
p.x = ((bounds.x + bounds.width) - radius) + speed;
} else if (p.x <= bounds.x) {
speed *= -1;
p.x = bounds.x + speed;
}
p.y = bounds.y + (bounds.height - radius) / 2;
return speed;
}
public void paint(Graphics2D g) {
g.setColor(Color.RED);
g.fillOval(0, 0, radius, radius);
}
}
}
My move method doesn't care if you've past the boundaries as it will reposition the ball back to sit within side those boundaries
public int move(int speed, Rectangle bounds) {
// Apply the delta
p.x += speed;
// Have we passed beyond the right side??
if (p.x + radius >= (bounds.x + bounds.width)) {
speed *= -1;
p.x = ((bounds.x + bounds.width) - radius) + speed;
// Have we past beyond the left side??
} else if (p.x <= bounds.x) {
speed *= -1;
p.x = bounds.x + speed;
}
p.y = bounds.y + (bounds.height - radius) / 2;
return speed;
}
Play around with the speed and see what you get ;)