Slick2d/LWJGL - Making a simple pong game issues - java

This is my class:
public class Play extends BasicGameState{
public int state;
private Input in;
private int rh = 100, rw = 10;//racket - Width , Height
private boolean left;//trye if the ball is going left
Ball b;//the ball
Guy p1,p2;//the players
public Play(int state)
{
this.state = state;
}
#Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException
{
Resources.init();
b = new Ball();
b.w = 20;
b.h = 20;
b.x = 800 / 2 - (b.w / 2);
b.y = 600 / 2 - (b.h / 2);
p1 = new Guy();
p2 = new Guy();
p1.x = 10;
p2.x = 780;//idk why 790 did not work
p1.y = 600 / 2 - (rh / 2);
p2.y = p1.y;
left = true;
b.ny = 0;
}
#Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException
{//just render
g.fillRect(p1.x, p1.y, rw, rh);
g.fillRect(p2.x, p2.y, rw, rh);
g.fillRect(b.x, b.y, b.w, b.h);
//g.drawImage(Resources.racket, p1.x, p1.y);
//g.drawImage(Resources.racket, p2.x, p2.y);
//g.drawImage(b.i , b.x , b.y);
debug();
}
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException
{
in = gc.getInput();//update input
if(Keyboard.isKeyDown(Keyboard.KEY_W))
{//update racket coordinates if keys are down
p1.y += delta * .1f;
}
if(Keyboard.isKeyDown(Keyboard.KEY_S))
{
p1.y += delta * .1f;
}
if(Keyboard.isKeyDown(Keyboard.KEY_UP))
{
p2.y -= delta * .1f;
}
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN))
{
p2.y += delta * .1f;
}
if(left)
{//collision detection (including setting angle to the ball if it doesnt hit the exact center of the racket)
if(b.x <= p1.x + rw && b.y <= p1.y + rh && b.y >= p1.y)
{
if(b.y + b.h == p1.x + (rh / 2))
{
b.ny = 0;
}
else if(b.y + b.h < p1.x + (rh / 2))
{
int d = p1.y + (rh / 2) - b.y;
b.ny = - d / 500;
}
else if(b.y + b.h > p1.x + (rh / 2))
{
int d = p1.y + rh - b.y;
b.ny = d / 500;
}
left = false;
}
}
else
{
if(b.x >= p2.x + rw && b.y <= p2.y + rh && b.y >= p2.y)
{
if(b.y + b.h == p2.x + (rh / 2))
{
b.ny = 0;
}
else if(b.y + b.h < p2.x + (rh / 2))
{
int d = p2.y + (rh / 2) - b.y;
b.ny = - d / 500;
}
else if(b.y + b.h > p2.x + (rh / 2))
{
int d = p2.y + rh - b.y;
b.ny = d / 500;
}
left = true;
}
}
if(left)
{//set the images
b.i = Resources.ball_move_left;
}
else
{
b.i = Resources.ball_move_right;
}
if(b.y <= 0 || b.y >= 600)
{//add "walls" on floor and ceiling
b.ny = - b.ny;
}
if(left)
{//update ball X coordinate
b.x -= delta * .1f;
}
else
{
b.x += delta * .1f;
}
b.y += b.ny * delta * .1f;//update ball Y coordinate
}
#Override
public int getID()
{
return state;
}
private void debug()
{
System.out.println("P1 : X:" + p1.x + " Y:" + p1.y);
System.out.println("P2 : X:" + p2.x + " Y:" + p2.y);
System.out.println("BALL : X:" + b.x + " Y:" + b.y);
}
}
For some weird reason I cant move the rackets up having a Y less than 0 and I also cant move them down at ALL. Here is the other classes (Ball - Guy)
public class Guy {
public int x,y;
}
public class Ball {
public int x,y,w,h,ny;
public Image i;
}
The ball also stops upon touching the left racket. It does not go back. There seems to be an issue with the x+= ... lines of code. I added debug messages , the messages print but the coordinates dont get an update!
I believe there is some bug with the whole code - working on it a whole day , did not find any errors :/

The problem is potentially in lines like:
b.x += delta * .1f;
Where you are taking a float and adding/subtracting it from an integer. It is possible that the Java engine performs a cast on the float data to turn it into an integer, which will loose data, and could cause the program to be non-responsive.
Additionally, you may want to move some of that procedural code that you have duplicated many times into the classes to improve the Object Oriented nature of this program.

Related

Unknown NullPointerException 10 ignore> [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
My code is:
public void move() {
moveX();
moveY();
}
public void moveX() {
if(xMove > 0) {
int tx = (int) (x + xMove + bounds.x + bounds.width) / Tile.TILEWIDTH;
if(!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT) && !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {
x += xMove;
}
} else if(xMove < 0) {
int tx = (int) (x + xMove + bounds.x) / Tile.TILEWIDTH;
if(!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT) && !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {
x += xMove;
}
}
}
public void moveY() {
if(yMove < 0) {
int ty = (int) (y + yMove + bounds.y + bounds.height) / Tile.TILEHEIGHT;
if(!collisionWithTile((int) (x + bounds.x) / Tile.TILEHEIGHT, ty) && !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)) {
y += yMove;
}
}
if(yMove > 0) {
int ty = (int) (y + yMove + bounds.y) / Tile.TILEHEIGHT;
if(!collisionWithTile((int) (x + bounds.x) / Tile.TILEHEIGHT, ty) && !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)) {
y += yMove;
}
}
}
protected boolean collisionWithTile(int x, int y) {
return room.getTile(x, y).isSolid();
}
but when I run it I get a NullPointerException with this StackTrace:
Exception in thread "Thread-0" java.lang.NullPointerException
at com.pixelandbitgames.entities.creature.Creature.collisionWithTile(Creature.java:69)
at com.pixelandbitgames.entities.creature.Creature.moveX(Creature.java:41)
at com.pixelandbitgames.entities.creature.Creature.move(Creature.java:27)
at com.pixelandbitgames.entities.creature.Player.tick(Player.java:19)
at com.pixelandbitgames.states.GameState.tick(GameState.java:23)
at com.pixelandbitgames.game.Game.tick(Game.java:72)
at com.pixelandbitgames.game.Game.run(Game.java:113)
at java.lang.Thread.run(Thread.java:748)
I do not see where this is coming from as collisionWithTile has all its parameters filled. If anyone can help me that would be appriciated. if anyone needs any thing else to help I will deliver. My other classes seem fine and it is just this one. This happens when I try to move. my code for Room.getTile is here:
public Tile getTile(int x, int y) {
if(x < 0 || y < 0 || x >= width || y >= height)
return Tile.floorTile;
Tile t = Tile.tiles[tiles[x][y]];
if(t == null)
return Tile.floorTile;
return t;
}
and this has no way to return null. Is solid is just a return true unless it is overridden.
public boolean isSolid() {
return false;
}
Either room is null, or room.getTile(x, y) returns null. You haven't pasted the relevant bits of those, making it impossible to give more information.

MouseEvent getPoint(), Math.asin(), and coordinates problems

I'm having trouble with the MouseEvent getPoint() method, the Math.asin() method, and just in general with coordinates. I am trying to create multiple objects called "Laser" to get fired from the "playerRobot". A rectangle is created around the playerRobot and the tempR.getCenterX and tempR.getCenterY are used to construct the point at the center of the playerRobot's location. The MouseEvent getPoint() is used to get the location of the mouse relative to the focused component. In the Laser class, two methods called getPointX(int y) and getPointY(int x) return a point with the respective x and y values corresponding to the given y or x value. I.e., getPointX(int y) returns a point with y and its corresponding x value. These methods do this by finding the linear equation between the given point of the playerRobot and the mouse. Then, the Laser is supposed to be drawn at the playerRobot point and redrawn to follow its linear equation to the mouse's point and continue on the linear equation until it reaches the borders of the component. However, depending on the angle at which the Laser is fired, it does not seem to always do this. Also, sometimes the Laser does not fire at all, sometimes it fires in the wrong direction or at the wrong angle, and sometimes it is longer than 50 pixels, which is always supposed to be the length of the Laser.
TL;DR: The Laser does not always fire from the playerRobot and does not always follow the linear line to the mouse's point, sometimes fires in the wrong direction or at the wrong angle, and sometimes is longer than 50 pixels.
Here is the code in the GameCanvas class that creates a new Laser object, followed by the code in the Laser class:
GameCanvas:
package application;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.shape.Line;
import javax.swing.*;
public class GameCanvas extends JPanel implements ActionListener, KeyListener, MouseListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX = 0, velY = 0;
boolean keyPress = false;
int code = 0;
long time = 1;
int currAIDelete = -1;
int currPlayerDelete = -1;
Graphics gr;
Point mousePoint = new Point();
AffineTransform oldTransform = new AffineTransform();
public GameCanvas() {
t.start();
addKeyListener(this);
addMouseListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
if(GameGUI.startScreen != null) {x = GameGUI.startScreen.imageLocationList.get(4).x; y = GameGUI.startScreen.imageLocationList.get(4).y; velX = 0; velY = 0;}
}
public void paintComponent(Graphics g) {
gr = g;
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(!GameGUI.getGameOver()) {
if(g2 != null) {
g2.drawImage(new javax.swing.ImageIcon(getClass().getResource(GameGUI.startScreen.imageList.get(7))).getImage(), (int) (x + 0.5), (int) (y + 0.5 + 64), GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(7).width, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(7).height, this);
g2.drawImage(new javax.swing.ImageIcon(getClass().getResource(GameGUI.startScreen.imageList.get(6))).getImage(), (int) (x + 0.5), (int) (y + 0.5 + 16), GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(6).width, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(6).height, this);
g2.drawImage(new javax.swing.ImageIcon(getClass().getResource(GameGUI.startScreen.imageList.get(5))).getImage(), (int) (x + 0.5), (int) (y + 0.5 + 16), GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(5).width, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(5).height, this);
g2.drawImage(new javax.swing.ImageIcon(getClass().getResource(GameGUI.startScreen.imageList.get(4))).getImage(), (int) (x + 0.5), (int) (y + 0.5), GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(4).width, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(4).height, this);
for(int i = 3; i >= 0; i--)
g2.drawImage(new javax.swing.ImageIcon(getClass().getResource(GameGUI.startScreen.imageList.get(i))).getImage(), GameGUI.startScreen.imageLocationList.get(i).x, GameGUI.startScreen.imageLocationList.get(i).y, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(i).width, GameGUI.startScreen.DEFAULT_SCALED_IMAGE_SIZE_LIST.get(i).height, this);
Color tempColor = g2.getColor();
g2.setColor(tempColor);
GameGUI.startScreen.healthBar();
tempColor = g2.getColor();
GameGUI.startScreen.healthBarGlyphVector = new Font("Tahoma", 0, 11).createGlyphVector(new FontRenderContext(null, true, false), String.valueOf(GameGUI.startScreen.playerHealth));
g2.setColor(GameGUI.startScreen.playerHealthBarColor);
g2.drawGlyphVector(GameGUI.startScreen.healthBarGlyphVector, (int) (x + 40 - GameGUI.startScreen.healthBarGlyphVector.getNumGlyphs() * (double) GameGUI.startScreen.healthBarGlyphVector.getFont().getSize() / 2 + 0.5), (long) (y + 0.5) - 20);
GameGUI.startScreen.playerHealthBar.setLocation((int) (x + 0.5), (int) (y + 0.5) - 10);
g2.draw(GameGUI.startScreen.playerHealthBar);
g2.fill(GameGUI.startScreen.playerHealthBar);
GameGUI.startScreen.healthBarGlyphVector = new Font("Tahoma", 0, 11).createGlyphVector(new FontRenderContext(null, true, false), String.valueOf(GameGUI.startScreen.aiHealth));
g2.setColor(GameGUI.startScreen.aiHealthBarColor);
g2.drawGlyphVector(GameGUI.startScreen.healthBarGlyphVector, (int) (GameGUI.gameResources.getAIRobot().getLocation().get(0).x + 40 - GameGUI.startScreen.healthBarGlyphVector.getNumGlyphs() * (double) GameGUI.startScreen.healthBarGlyphVector.getFont().getSize() / 2 + 0.5), GameGUI.gameResources.getAIRobot().getLocation().get(0).y - 20);
GameGUI.startScreen.aiHealthBar.setLocation(GameGUI.gameResources.getAIRobot().getLocation().get(0).x, GameGUI.gameResources.getAIRobot().getLocation().get(0).y - 10);
g2.draw(GameGUI.startScreen.aiHealthBar);
g2.fill(GameGUI.startScreen.aiHealthBar);
g2.setColor(tempColor);
if(GameGUI.gameResources.playerLaserList != null) {
for(int i = GameGUI.gameResources.playerLaserList.size() - 1; i >= 0; i--) {
tempColor = g2.getColor();
oldTransform = g2.getTransform();
g2.setColor(Color.RED);
g2.setStroke(new BasicStroke(10));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine((int) (GameGUI.gameResources.playerLaserList.get(i).getCurrentLine().getStartX() + 0.5), (int) (GameGUI.gameResources.playerLaserList.get(i).getCurrentLine().getStartY() + 0.5), (int) (GameGUI.gameResources.playerLaserList.get(i).getCurrentLine().getEndX() + 0.5), (int) (GameGUI.gameResources.playerLaserList.get(i).getCurrentLine().getEndY() + 0.5));
g2.setTransform(oldTransform);
g2.setColor(tempColor);
}
}
if(GameGUI.gameResources.aiLaserList != null) {
for(int i = GameGUI.gameResources.aiLaserList.size() - 1; i >= 0; i--) {
tempColor = g2.getColor();
oldTransform = g2.getTransform();
g2.setColor(Color.RED);
g2.setStroke(new BasicStroke(10));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine((int) (GameGUI.gameResources.aiLaserList.get(i).getCurrentLine().getStartX() + 0.5), (int) (GameGUI.gameResources.aiLaserList.get(i).getCurrentLine().getStartY() + 0.5), (int) (GameGUI.gameResources.aiLaserList.get(i).getCurrentLine().getEndX() + 0.5), (int) (GameGUI.gameResources.aiLaserList.get(i).getCurrentLine().getEndY() + 0.5));
g2.setTransform(oldTransform);
g2.setColor(tempColor);
}
}
}
}
else try {
if(GameGUI.startScreen.checkGameOver() && GameGUI.startScreen.getGameOverVector() != null) {
g2.drawGlyphVector(GameGUI.startScreen.getGameOverVector(), (int) (380 - GameGUI.startScreen.getGameOverVector().getNumGlyphs() * (double) GameGUI.startScreen.healthBarGlyphVector.getFont().getSize() / 2 + 0.5), 250 - 29);
GameGUI.startScreen.imageList = new ArrayList <String> (Arrays.asList());
}
} catch (GameResourceException ex) {
Logger.getLogger(GameCanvas.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void actionPerformed(ActionEvent e) {
if((code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN || code == KeyEvent.VK_LEFT || code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_W || code == KeyEvent.VK_S || code == KeyEvent.VK_A || code == KeyEvent.VK_D) && keyPress && x >= 0 && x <= 680 && y >= 0 && y <= 400) {
x += velX;
y += velY;
GameGUI.gameResources.getPlayerRobot().setLocation(new Point((int) (x + 0.5), (int) (y + 0.5)), new Point((int) (x + 0.5 + 37), (int) (y + 0.5 + 99)));
}
else {
if(x < 0) x++;
if(x > 680) x--;
if(y < 0) y++;
if(y > 400) y--;
}
if(GameGUI.gameResources.playerLaserList != null) {
for(int i = GameGUI.gameResources.playerLaserList.size() - 1; i >= 0; i--) {
Rectangle tempRectAI = new Rectangle(GameGUI.gameResources.getAIRobot().getLocation().get(0).getLocation().x, GameGUI.gameResources.getAIRobot().getLocation().get(0).getLocation().y, GameGUI.gameResources.getAIRobot().getLocation().get(1).getLocation().x, GameGUI.gameResources.getAIRobot().getLocation().get(1).getLocation().y);
Line line = GameGUI.gameResources.playerLaserList.get(i).getCurrentLine();
if(GameGUI.gameResources.playerLaserList.get(i).getLocation().x + 50 < 0 || GameGUI.gameResources.playerLaserList.get(i).getLocation().x > 762 || GameGUI.gameResources.playerLaserList.get(i).getLocation().y + 50 < 0 || GameGUI.gameResources.playerLaserList.get(i).getLocation().y > 500 || tempRectAI.intersectsLine(line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY()))
GameGUI.gameResources.playerLaserList.remove(i);
else {
GameGUI.gameResources.playerLaserList.get(i).move(time);
}
}
}
if(GameGUI.gameResources.aiLaserList != null) {
for(int i = GameGUI.gameResources.aiLaserList.size() - 1; i >= 0; i--) {
Rectangle tempRectPlayer = new Rectangle(GameGUI.gameResources.getPlayerRobot().getLocation().get(0).getLocation().x, GameGUI.gameResources.getPlayerRobot().getLocation().get(0).getLocation().y, GameGUI.gameResources.getPlayerRobot().getLocation().get(1).getLocation().x, GameGUI.gameResources.getPlayerRobot().getLocation().get(1).getLocation().y);
Line line = GameGUI.gameResources.aiLaserList.get(i).getCurrentLine();
if(GameGUI.gameResources.aiLaserList.get(i).getLocation().x + 50 < 0 || GameGUI.gameResources.aiLaserList.get(i).getLocation().x > 762 || GameGUI.gameResources.aiLaserList.get(i).getLocation().y + 50 < 0 || GameGUI.gameResources.aiLaserList.get(i).getLocation().y > 500 || tempRectPlayer.intersectsLine(line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY()))
GameGUI.gameResources.aiLaserList.remove(i);
else {
GameGUI.gameResources.aiLaserList.get(i).move(time);
}
}
}
repaint();
}
public void up() {
velY = -1.5;
velX = 0;
}
public void down() {
velY = 1.5;
velX = 0;
}
public void left() {
velX = -1.5;
velY = 0;
}
public void right() {
velX = 1.5;
velY = 0;
}
public void keyPressed(KeyEvent e) {
keyPress = true;
code = e.getKeyCode();
if(code == KeyEvent.VK_UP || code == KeyEvent.VK_W) {
up();
}
if(code == KeyEvent.VK_DOWN || code == KeyEvent.VK_S) {
down();
}
if(code == KeyEvent.VK_RIGHT || code == KeyEvent.VK_D) {
right();
}
if(code == KeyEvent.VK_LEFT || code == KeyEvent.VK_A) {
left();
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
keyPress = false;
}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent evt) {
mousePoint = evt.getPoint();
if(GameGUI.getGameOver()) GameGUI.gameResources.resetForNextLevel();
else {
GameGUI.gameResources.getPlayerRobot().setLocation(new Point((int) (x + 0.5), (int) (y + 0.5)), new Point((int) (x + 0.5 + 37), (int) (y + 0.5 + 99)));
Rectangle tempR = new Rectangle(GameGUI.gameResources.getPlayerRobot().getLocation().get(0).x, GameGUI.gameResources.getPlayerRobot().getLocation().get(0).y, GameGUI.gameResources.getPlayerRobot().getLocation().get(1).x, GameGUI.gameResources.getPlayerRobot().getLocation().get(1).y);
GameGUI.gameResources.playerLaserList.add(new Laser(new Point((int) (tempR.getCenterX() + 0.5), (int) (tempR.getCenterY() + 0.5)), evt.getPoint(), GameGUI.gameResources));
}
}
}
Laser:
package application;
import java.awt.Point;
import javafx.scene.shape.Line;
public class Laser {
private Point point1;
private Point point2;
private Point currentPoint;
private double angle;
private Line laserLine;
private Point farEnd;
private Point farStart;
private double x1, x2, y1, y2, m, y3, x3;
private GameResources gameResources;
public Laser(Point tempPoint1, Point tempPoint2, GameResources tempGR) {
gameResources = tempGR;
currentPoint = point1 = tempPoint1;
point2 = tempPoint2;
double leg1 = point2.x - point1.x;
double leg2 = point2.y - point1.y;
double hyp = Math.sqrt(Math.pow(leg1, 2) + Math.pow(leg2, 2));
angle = Math.asin(leg2 / hyp);
if(angle < 0) angle = 2 * Math.abs(angle);
farEnd = getPointX(460);
farStart = getPointX(0);
laserLine = new Line(farStart.x, farStart.y, farEnd.x, farStart.y);
x1 = tempPoint1.x;
y1 = tempPoint1.y;
x2 = tempPoint2.x;
y2 = tempPoint2.y;
m = (y2 - y1) / (x2 - x1);
x3 = 0;
y3 = 0;
}
public Point getInitialLocation() {
return point1;
}
public Point getLocation() {
return currentPoint;
}
public double getAngle() {
return angle;
}
public Line getLine() {
return laserLine;
}
public Line getCurrentLine() {
Line currentLine = new Line();
if(getAngle() < Math.PI && getAngle() > 0)
currentLine = new Line((int) (currentPoint.x + 0.5), (int) (currentPoint.y + 0.5), (int) (getPointX((int) (currentPoint.y + 0.5) + (int) (Math.sin(angle) * 50 + 0.5)).x + 0.5), (int) (currentPoint.y + 0.5) + (int) (Math.sin(angle) * 50 + 0.5));
else if(getAngle() > Math.PI && getAngle() < 2 * Math.PI)
currentLine = new Line((int) (currentPoint.x + 0.5), (int) (currentPoint.y + 0.5), (int) (getPointX((int) (currentPoint.y + 0.5) - (int) (Math.sin(angle) * 50 + 0.5)).x + 0.5), (int) (currentPoint.y + 0.5) - (int) (Math.sin(angle) * 50 + 0.5));
System.out.println(currentLine.getStartX() + " " + currentLine.getStartY() + " " + point1);
return currentLine;
}
public void setLocation(Point tempLocation) {
currentPoint = tempLocation;
}
public Point getPointY(int x) {
if(x1 == x2 && y1 != y2) return null;
else if(m < 0) y3 = ((y2 - y1) / (x2 - x1)) * (double) x - (x2 * ((y2 - y1) / (x2 - x1)) - y2);
else if(m > 0) y3 = ((y2 - y1) / (x2 - x1)) * (double) x + (x2 * ((y2 - y1) / (x2 - x1)) - y2);
else if(m == 0) y3 = ((y2 - y1) / (x2 - x1)) * (double) x;
return new Point(x, (int) (y3 + 0.5));
}
public Point getPointX(int y) {
if(x1 == x2 && y1 != y2) return new Point((int) (x1 + 0.5), y);
else if(m < 0) x3 = ((double) y + (x2 * ((y2 - y1) / (x2 - x1)) - y2)) / ((y2 - y1) / (x2 - x1));
else if(m > 0) x3 = ((double) y - (x2 * ((y2 - y1) / (x2 - x1)) - y2)) / ((y2 - y1) / (x2 - x1));
else if(m == 0) x3 = (double) y / (((y2 - y1) / (x2 - x1)));
return new Point((int) (x3 + 0.5), (int) (y + 0.5));
}
public Line move(double time) {
//old algorithm
/*double x = 0, y = 0;
if(y2 > y1) {
y = currentPoint.y + gameResources.getLaserSpeed() * time;
currentPoint = getPointX((int) y);
}
else if(y2 < y1) {
y = currentPoint.y - gameResources.getLaserSpeed() * time;
currentPoint = getPointX((int) y);
}
else if(y2 == y1 && x2 > x1) {
x = currentPoint.x + gameResources.getLaserSpeed() * time;
currentPoint = getPointY((int) x);
}
else if(y2 == y1 && x2 < x1) {
x = currentPoint.x - gameResources.getLaserSpeed() * time;
currentPoint = getPointY((int) x);
}*/
//new algorithm
if(getAngle() < Math.PI / 2 && getAngle() > 0) {
System.out.println("(1) First quad");
setLocation(getPointY((int) (getLocation().x + 1 + 0.5)));
}
else if(getAngle() < Math.PI && getAngle() > Math.PI / 2) {
System.out.println("(2) Second quad");
setLocation(getPointY((int) (getLocation().x - 1 - 0.5)));
}
else if(getAngle() > Math.PI && getAngle() < 3 * Math.PI / 2) {
System.out.println("(3) Third quad");
setLocation(getPointY((int) (getLocation().x - 1 - 0.5)));
}
else if(getAngle() > 3 * Math.PI / 2 && getAngle() < 2 * Math.PI) {
System.out.println("(4) Fourth quad");
setLocation(getPointY((int) (getLocation().x + 1 + 0.5)));
}
else if(getAngle() == 2 * Math.PI || getAngle() == 0)
setLocation(new Point((int) (getLocation().x + 1 + 0.5), (int) (getLocation().y + 0.5)));
else if(getAngle() == Math.PI)
setLocation(new Point((int) (getLocation().x - 1 - 0.5), (int) (getLocation().y + 0.5)));
else if(getAngle() == Math.PI / 2)
setLocation(new Point((int) (getLocation().x + 0.5), (int) (getLocation().y + 1 + 0.5)));
else if(getAngle() == 3 * Math.PI / 2)
setLocation(new Point((int) (getLocation().x + 0.5), (int) (getLocation().y - 1 - 0.5)));
return getCurrentLine();
}
public void setGameResources(GameResources tempGR) {
gameResources = tempGR;
}
}

Image weirdness with slick2d graphics translation

I am making a game and I noticed whenever I use the graphics.translate function and after the translate this happens to the images.
Before Translation
After Translation
I was wondering if there is anyway to fix that or anyone else has the same issue. All these sprites are rendered from a spritesheet
EDIT: Translate code
public void translate(Graphics g, GameContainer container, int delta) {
g.translate(((container.getWidth() / 2) - this.x), ((container.getHeight() / 2) - this.y));
}
public void update(GameContainer container, int type){
if (type == 0) {
x = p.getX(); //p is the player
y = p.getY();
} else if (type == 1) {
x = player.x;
y = player.y;
}
if (offset) {
if (this.x - container.getWidth() / 2 < offsetMin[0]) {
x = offsetMin[0] + container.getWidth() / 2;
} else if (this.x + container.getWidth() / 2 > offsetMax[0]) {
x = offsetMax[0] - container.getWidth() / 2;
}
if (this.y - container.getHeight() / 2 < offsetMin[1]) {
y = offsetMin[1] + container.getHeight() / 2;
} else if (this.y + container.getHeight() > offsetMax[1]) {
y = offsetMax[1] - container.getHeight() / 2;
}
}
}
Try casting the x and y parameters for g.translate() to ints. That would eliminate any rounding errors where tiles don't end up on perfect pixel coords (IE 4, not 4.2).
Moved answer from comments to answer so it can be marked as accepted by OP

How to make an object follow a mouse (java)

I need help with trying to make the circle in this program continuously follow my mouse's x and y coordinates.It does follow my mouse in certain points. I think this is due to the fact that i am using the slope between the two coordinates in my program. An example of the issue would be that it will go in the exact opposite direction and move away from my mouse if I am to the right of its x position. Can someone give me some guidance?
The ObjectMove class.
import java.awt.*;
import hsa.LASSConsole;
public class ObjectMove
{
static LASSConsole c; // The output console
public static void main (String[] args) throws java.lang.InterruptedException
{
c = new LASSConsole ();
double xcoord = c.maxx () / 2;
double ycoord = c.maxy () / 2;
double mouseX;
double mouseY;
double vely;
double velx;
double m;
int d = 20;
while (true)
{
mouseX = c.GetMouseX ();
mouseY = c.GetMouseY ();
m = ((mouseY - ycoord) / (mouseX - xcoord));
if (((mouseX - xcoord) / -1) == (mouseX - xcoord) / (mouseX - xcoord))
{
velx = -1;
}
else
{
velx = 1;
}
if (((mouseY - ycoord) / -1) == (mouseY - ycoord) / (mouseY - ycoord) && velx == -1)
{
vely = -m;
}
else if ((((mouseY - ycoord) / -1) == (mouseY - ycoord) / (mouseY - ycoord)) && velx == 1)
{
vely = m;
}
else if ((((mouseY - ycoord) / -1) != (mouseY - ycoord) / (mouseY - ycoord)) && velx == -1)
{
vely = -m;
}
else if (mouseX - xcoord == 0)
{
if (mouseY > ycoord)
{
vely = 1;
velx = 0;
}
else
{
vely = -1;
}
}
else
{
vely = m;
}
c.setColor (Color.black);
xcoord = xcoord - velx;
ycoord = ycoord - vely;
c.fillOval ((int) xcoord, (int) ycoord, (int) d, (int) d);
Thread.sleep (100);
c.setColor (Color.white);
c.fillOval ((int) xcoord, (int) ycoord, (int) d, (int) d);
}
} // main method
} // ObjectMove class
`

LibGdx Mouse Position relative to Orthographic Camera instead of Screen

Basically I wrote a "Dota like Style" based on the OrthographicCamera from libgdx.
You can test it out for youself here is the class.
I am using this to draw a TiledMap, and I have and array of tiles corresponding with the graphical tiles, however if I move the mouse, and with that the camera.
The coordinates off the mouse and the tiles are completely different.
Gdx.input x and y get their coordinates relative to the screen and not where the mouse is in the world relative to the camera.
I can't figure out a way to get the mouse position relative to the camera, so that if I move the camera I won't just get the regular mouse coordinates, but the actual world coordinates that the camera is showing, and where my mouse is located within the confines of the view of the camera relative to the world.
public class DotaCamera extends OrthographicCamera {
private float xmin;
private float xmax;
private float ymin;
private float ymax;
private float x;
private float y;
private int Width = Gdx.graphics.getWidth();;
private int Height = Gdx.graphics.getHeight();
private int camSpeedMax = 16;
private float camAcceleration = 0.3f;
private int camSpeedSmoother = 3;
private float camVelocityX = 0;
private float camVelocityY = 0;
private float fZoomMax = 1f;
private float fZoomMin = 0.5f;
private float fZoomSpeed = 0.03f;
public DotaCamera() {
this(0, 0, 0, 0);
}
public DotaCamera(float xmin, float xmax, float ymin, float ymax) {
super();
setBounds(xmin, xmax, ymin, ymax);
}
public void setBounds(float xmin, float xmax, float ymin, float ymax) {
this.xmin = xmin;
this.xmax = xmax;
this.ymin = ymin;
this.ymax = ymax;
}
public void setPosition(float x, float y) {
setPosition(x, y, 0);
}
public void setPosition(float x, float y, float z) {
position.set(x, y, z);
this.x = x;
this.y = y;
fixBounds();
}
private void fixBounds() {
if (position.x < xmin + viewportWidth / 2) {
position.x = xmin + viewportWidth / 2;
}
if (position.x > xmax - viewportWidth / 2) {
position.x = xmax - viewportWidth / 2;
}
if (position.y < ymin + viewportHeight / 2) {
position.y = ymin + viewportHeight / 2;
}
if (position.y > ymax - viewportHeight / 2) {
position.y = ymax - viewportHeight / 2;
}
}
/**
* Controls the zoom of the of the camera.
*/
public void updateZoom() {
int mouseWheelMovement = Mouse.getDWheel();
if (mouseWheelMovement > 0) {
if (this.zoom > fZoomMin) {
this.zoom -= fZoomSpeed;
} else {
this.zoom = fZoomMin;
}
}else if(mouseWheelMovement < 0){
if (this.zoom < fZoomMax) {
this.zoom += fZoomSpeed;
} else {
this.zoom = fZoomMax;
}
}
}
/**
* Update And move the Camera DOTA Stylized movement.
*/
public void updateAndMove() {
float dt = Gdx.graphics.getDeltaTime();
int MouseX = Mouse.getX(); // Get MouseX
int MouseY = Height - Mouse.getY(); // Get MouseY
int camSpeedX = 0;
int camSpeedY = 0;
String horizontalDirection = getMoveLeftRight(MouseX); // Get
// horizontalDirection
String verticalDirection = getMoveUpDown(MouseY); // Get
// verticalDirection
/* * * * * * * *
* Decide what to do with the horizontalDirection.
*/
switch (horizontalDirection) {
case "left":
camSpeedX = ((Width / 2) - (MouseX + (Width / 4)))
/ camSpeedSmoother; // Create Speed -X
camSpeedX = ((camSpeedX > camSpeedMax) ? camSpeedMax : camSpeedX); // Limit
// the
// speed.
if (camVelocityX < camSpeedX)
camVelocityX += camAcceleration;
break;
case "right":
camSpeedX = (((MouseX + (Width / 4)) - ((Width / 4) * 3)) - (Width / 4))
/ camSpeedSmoother; // Create speed +X.
camSpeedX = ((camSpeedX > camSpeedMax) ? camSpeedMax : camSpeedX); // Limit
// the
// speed.
if (camVelocityX < camSpeedX)
camVelocityX += camAcceleration; // Accelerate
camSpeedX *= -1; // To negate the speed.
break;
case "":
camVelocityX = 0;
break;
}
/* * * * * * * *
* Decide what to do with the verticalDirection.
*/
switch (verticalDirection) {
case "up":
camSpeedY = (Height / 4) - MouseY; // Create speed -Y
camSpeedY = ((camSpeedY > camSpeedMax) ? camSpeedMax : camSpeedY); // Limit
// the
// speed.
if (camVelocityY < camSpeedY)
camVelocityY += camAcceleration;
camSpeedY *= -1;
break;
case "down":
camSpeedY = (((MouseY + (Height / 4)) - ((Height / 4) * 3)) - (Height / 4))
/ camSpeedSmoother; // Create speed +Y.
camSpeedY = ((camSpeedY > camSpeedMax) ? camSpeedMax : camSpeedY); // Limit
// the
// speed.
if (camVelocityY < camSpeedY)
camVelocityY += camAcceleration;
break;
case "":
camVelocityY = 0;
break;
}
// System.out.println("vX:" +camVelocityX+ "vY: " +camVelocityY+ "sX: "
// +camSpeedX+ "sY: " +camSpeedY);
this.position.x -= (camVelocityX * camSpeedX) * dt;
this.position.y -= (camVelocityY * camSpeedY) * dt;
this.update();
}
/**
* Get the X-Axial Direction.
*
* #param MouseX
* #return Direction
*/
private String getMoveLeftRight(int MouseX) {
if (MouseX + (Width / 4) < Width / 2) {// Needs to move left?
return "left";
} else if (MouseX > (Width / 4) * 3) {// Needs to move right?
return "right";
}
return "";
}
/**
* Get the Y-Axial Direction.
*
* #param MouseY
* #return Direction
*/
private String getMoveUpDown(int MouseY) {
if (MouseY < Height / 4) {// Needs to move up?
return "up";
} else if (MouseY > (Height / 4) * 3) {// Needs to move down?
return "down";
}
return "";
}
Came across this problem and discovered the answer here:
https://gamedev.stackexchange.com/questions/27786/camera-coordinate-to-screen-coordinate
Supposedly, using Camera.unproject(Vector3 screenCoords) is the correct way of doing this.
My solution looks like this:
Vector3 getMousePosInGameWorld() {
return camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
}
I hope you found the solution to what you need here
https://gamedev.stackexchange.com/questions/60703/libgdx-how-to-get-mouse-position-relative-to-a-tiled-map
maybe here
Get cursor position in LIBGDX
or here
http://www.netthreads.co.uk/2012/01/31/libgdx-example-of-using-scene2d-actions-and-event-handling/

Categories