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

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

Related

JAVA: mouseDragged getX and getY raw data erratic

I am trying to code a paint like program (for fun), but to challenge myself I tried to do it using setRGB method, but I see that when I move the mouse fast the behavior of the stroke gets erratic, do you know how to "soft" the data get from methods getX and getY? or why I am getting random points colored
Thank you in advance and sorry for my english. :)
public class Canvas extends JPanel implements ActionListener, MouseMotionListener, MouseListener {
int canvasW;
int canvasH;
BufferedImage imgCanvas;
int X1;
int Y1;
int X0;
int Y0;
int sizeCanvas = 10;
int expCanvas = 2 * sizeCanvas - 1;
public Canvas(int width, int height) {
canvasH = height;
canvasW = width;
setPreferredSize(new Dimension(width, height));
setBorder(BorderFactory.createLineBorder(Color.black));
setBackground(Color.white);
CanvasImage(width, height);
addMouseListener(this);
addMouseMotionListener(this);
}
public BufferedImage CanvasImage(int width, int height) {
imgCanvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
return imgCanvas;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(imgCanvas, null, null);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public void drawer() {
int deltaX = abs(X1 - X0);
int deltaY = abs(Y1 - Y0);
double m;
double b;
if (deltaX >= deltaY) {
if (deltaY == 0) {
m = 0;
} else {
m = (X0 - X1) / (Y0 - Y1);
}
b = Y0 - m * X0;
if (X1 > X0) {
for (int i = X0; i <= X1; i++) {
imgCanvas.setRGB(i, (int) (m * i + b), Color.BLACK.getRGB());
System.out.println(i + " ; " + (int) (m * i + b));
}
} else {
for (int i = X0; i >= X1; i--) {
imgCanvas.setRGB(i, (int) (m * i + b), Color.BLACK.getRGB());
System.out.println(i + " ; " + (int) (m * i + b));
}
}
} else {
if (deltaX == 0) {
m = 0;
} else {
m = (Y0 - Y1) / (X0 - X1);
}
b = X0 - m * Y0;
if (Y1 > Y0) {
for (int i = Y0; i <= Y1; i++) {
imgCanvas.setRGB((int) (m * i + b), i, Color.BLACK.getRGB());
}
} else {
for (int i = Y0; i >= Y1; i--) {
imgCanvas.setRGB((int) (m * i + b), i, Color.BLACK.getRGB());
}
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
X1 = e.getX();
Y1 = e.getY();
drawer();
repaint();
X0 = X1;
Y0 = Y1;
}
#Override
public void mousePressed(MouseEvent e) {
X0 = e.getX();
Y0 = e.getY();
}

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.

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
`

Slick2d/LWJGL - Making a simple pong game issues

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.

When processing Java mode convert to Java script mode, my 3D object doesn't show

I have a problem when I upload my sketch to website.
I write a processing program which is a 3D guiding library.This is my code.
//Camera Variables
float x,y,z;
float tx,ty,tz;
float rotX,rotY;
float mX, mY;
float frameCounter;
float xComp, zComp;
float angle;
//Movement Variables
int moveX;
int moveZ;
float vY;
boolean canJump;
boolean moveUP,moveDOWN,moveLEFT,moveRIGHT;
//check input
int m =0;
//Constants
int ground = 0;
int totalBoxes = 100;
int standHeight = 100;
int dragMotionConstant = 10;
int pushMotionConstant = 100;
int movementSpeed = 50; //Bigger number = slower
float sensitivity = 15; //Bigger number = slower
int stillBox = 100; //Center of POV, mouse must be stillBox away from center to move
float camBuffer = 10;
int cameraDistance = 1000; //distance from camera to camera target in lookmode... 8?
//Options
int lookMode = 8;
int spotLightMode = 4;
int cameraMode = 1;
int moveMode = 2;
void setup(){
size(800,600,P3D);
noStroke();
//dwa(#EDEDE8);
//Camera Initialization
//default
x = -28;
y = height/2;
y-= standHeight;
z = -4830;
tx = width/2;
ty = height/2;
tz = 0;
rotX = 0;
rotY = 0;
xComp = tx - x;
zComp = tz - z;
angle = 0;
//Movement Initialization
moveX = 0;
moveX = 0;
moveUP = false;
moveDOWN = false;
moveLEFT = false;
moveRIGHT = false;
canJump = true;
vY = 0;
}
void draw(){
if(z<-5000)
z=-5000;
if(z>9700)
z=9700;
//println(x,y,z ,mouseX , mouseY ,tx ,ty,tz);
//update frame
background(0);
lights();
if(m==1)
{
//rotateY(0.5);
fill(#EAFF0F);
textSize(50);
text("menu", x-100, y, z+300);
// rotateY(0.5);
//the point
pushMatrix();
fill(#FC1919);
translate(-28,300,4000);
box(10, 20000, -10);
popMatrix();
//the point
}
if(spotLightMode == 0)
lights();
else if(spotLightMode == 1)
spotLight(255,255,255,x,y-standHeight,z,tx,ty,tz,PI,1);
else if(spotLightMode == 2)
spotLight(255,255,255,x,y-standHeight-200,z,x+100,y+100,z,frameCounter/10,1);
else if(spotLightMode == 3)
spotLight(255,255,255,width/2,height/2-1000,0,width/2,height/2,0,PI,1);
else if(spotLightMode == 4)
{
pointLight(255,255,255,x,y,z);
}
/*
for(int i=1;i<=7;i++)
{
spotLight(255, 255, 255, -28, 2000, -5500+i*1875, 1, 1, 1, 360, 1);
}*/
//-5500 9500s
//back wall
pushMatrix();
fill(255);
translate(-28,300,-5500);
box(15000, 5000, -100);
popMatrix();
//back wall
//fount wall
pushMatrix();
fill(255);
translate(-28,300,10500);
box(15000, 5000, -100);
popMatrix();
//fount wall
//L1
bookshielf(800,-4000,7,1);
bookshielf(1000,-4000,7,1);
bookshielf(1200,-4000,7,1);
bookshielf(1400,-4000,7,1);
cameraUpdate();
locationUpdate();
jumpManager(10);
//Camera Mode 1 - Original
if(cameraMode == 1)
camera(x,y,z,tx,ty,tz,0,1,0);
//Camera Mode 2 - Matrix'd
/* if(cameraMode == 2){
beginCamera();
camera();
translate(x,y,z);
translate(0,2*-standHeight,0);
rotateX(rotY/100.0); //This seems to work o.o
rotateY(-rotX/100.0);
//rotateX(rotX/100.0);
endCamera();
}*/
//frameCounter++;
}
void cylinder(float w, float h, int sides)
{
float angle;
float[] x = new float[sides+1];
float[] z = new float[sides+1];
translate(0,100,-500);
//get the x and z position on a circle for all the sides
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x[i] = sin(angle) * w;
z[i] = cos(angle) * w;
}
//draw the top of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, -h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
}
endShape();
//draw the center of the cylinder
beginShape(QUAD_STRIP);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
vertex(x[i], h/2, z[i]);
}
endShape();
//draw the bottom of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], h/2, z[i]);
}
endShape();
}
public void bookshielf(int thex ,int thez ,int theheight ,int therotate)
{
fill(#938056);
if(theheight==7)
{
if(therotate==1)
{
//left
pushMatrix();
translate(thex,0,thez);
box(20, 500, -100);
popMatrix();
//right
pushMatrix();
translate(thex-200,0,thez);
box(20, 500, -100);
popMatrix();
//back
pushMatrix();
translate(thex-100,0,thez+40);
box(220, 500, -30);
popMatrix();
//middle side
for(int i=1;i<7;i++)
{
pushMatrix();
translate(thex-100,-250+71.5*i,thez-10);
box(220, 5, -100);
popMatrix();
}
//top
pushMatrix();
translate(thex-100,250,thez);
box(220, 10, -100);
popMatrix();
//block
pushMatrix();
translate(thex-100,-250,thez);
box(220, 10, -100);
popMatrix();
}
if(therotate==2)
{
//left
pushMatrix();
translate(thex,0,thez);
box(20, 500, -100);
popMatrix();
//right
pushMatrix();
translate(thex-200,0,thez);
box(20, 500, -100);
popMatrix();
//back
pushMatrix();
translate(thex-100,0,thez-40);
box(220, 500, -30);
popMatrix();
//middle side
for(int i=1;i<7;i++)
{
pushMatrix();
translate(thex-100,-250+71.5*i,thez+10);
box(220, 5, -100);
popMatrix();
}
//top
pushMatrix();
translate(thex-100,250,thez);
box(220, 10, -100);
popMatrix();
//block
pushMatrix();
translate(thex-100,-250,thez);
box(220, 10, -100);
popMatrix();
}
}
}
public void cameraUpdate(){
ty=constrain(dragMotionConstant, -100000, 500000);
//Drag-motion
if (lookMode == 1){
if(pmouseX > mouseX)
tx += dragMotionConstant;
else if (pmouseX < mouseX)
tx -= dragMotionConstant;
if(pmouseY > mouseY)
ty -= dragMotionConstant/1.5;
else if (pmouseY < mouseY)
ty += dragMotionConstant/1.5;
}
//Push-motion
else if (lookMode == 2){
if (mouseX > (width/2+pushMotionConstant))
tx += dragMotionConstant;
else if (mouseX < (width/2-pushMotionConstant))
tx -= dragMotionConstant;
if (mouseY > (height/2+pushMotionConstant))
ty += dragMotionConstant;
else if (mouseY < (height/2-pushMotionConstant))
ty -= dragMotionConstant;
}
//Push-motion V2 (Hopefully improved!)
else if (lookMode == 3){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if (abs(diffX) > pushMotionConstant)
tx += diffX/25;
if (abs(diffY) > pushMotionConstant)
ty += diffY/25;
}
//Push Motion V3 (For Camera-Mode 2)
else if (lookMode == 4){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
//println(diffX);
if (abs(diffX) > pushMotionConstant)
rotX += diffX/100;
if (abs(diffY) > pushMotionConstant)
rotY += diffY/100;//diffY/100;
}
//Push Motion V4.1 (Because it crashed and I lost V4.0 T.T
//Designed to work in cohesion with movement mode 2
else if (lookMode == 5){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = degrees(atan(xComp/zComp));
//---------DEBUG STUFF GOES HERE----------
//println("tx: " + tx);
//println("tz: " + tz);
// println("xC: " + xComp);
// println("zC: " + zComp);
// println("Angle: " +angle);
//--------------------------------------*/
if (angle < 45 && angle > -45 && zComp < 0)
tx += diffX/sensitivity;
else if (angle < 45 && angle > -45 && zComp > 0)
tx -= diffX/sensitivity;
//Left Sector
else if (angle > 45 && angle < 90 && xComp < 0 && zComp < 0)
tz -= diffX/sensitivity;
else if (angle >-90 && angle <-45 && xComp < 0 && zComp > 0)
tz -= diffX/sensitivity;
//Right Sector
else if (angle <-45 && angle >-90)
tz += diffX/sensitivity;
else if (angle < 90 && angle > 45 && xComp > 0 && zComp > 0)
tz += diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
//Lookmode 4.2
//Using a more proper unit circle.
else if (lookMode == 6){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
//---------DEBUG STUFF GOES HERE----------
// println("tx: " + tx);
// println("tz: " + tz);
// println("xC: " + xComp);
/// println("zC: " + zComp);
/// println("Angle: " +angle);
//--------------------------------------*/
//Looking 'forwards'
if ((angle >= 0 && angle < 45) || (angle > 315 && angle < 360))
tx += diffX/sensitivity;
//Looking 'left'
else if (angle > 45 && angle < 135)
tz += diffX/sensitivity;
//Looking 'back'
else if (angle > 135 && angle < 225)
tx -= diffX/sensitivity;
//Looking 'right'
else if (angle > 225 && angle < 315)
tz -= diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
//Lookmode 7, trying to get rid of the slowdown in the corners with a sorta-buffer thing
else if (lookMode == 7){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
//---------DEBUG STUFF GOES HERE----------
// println("tx: " + tx);
// println("tz: " + tz);
// println("xC: " + xComp);
// println("zC: " + zComp);
// println("Angle: " +angle);
//--------------------------------------*/
//Looking 'forwards'
if ((angle >= 0-camBuffer && angle < 45+camBuffer) || (angle > 315-camBuffer && angle < 360+camBuffer))
tx += diffX/sensitivity;
//Looking 'left'
else if (angle > 45-camBuffer && angle < 135+camBuffer)
tz += diffX/sensitivity;
//Looking 'back'
else if (angle > 135-camBuffer && angle < 225+camBuffer)
tx -= diffX/sensitivity;
//Looking 'right'
else if (angle > 225-camBuffer && angle < 315+camBuffer)
tz -= diffX/sensitivity;
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
else if (lookMode == 8){
int diffX = mouseX - width/2;
int diffY = mouseY - width/2;
if(abs(diffX) > stillBox){
xComp = tx - x;
zComp = tz - z;
angle = correctAngle(xComp,zComp);
angle+= diffX/(sensitivity*10);
if(angle < 0)
angle += 360;
else if (angle >= 360)
angle -= 360;
float newXComp = cameraDistance * sin(radians(angle));
float newZComp = cameraDistance * cos(radians(angle));
tx = newXComp + x;
tz = -newZComp + z;
//---------DEBUG STUFF GOES HERE----------
/*println("tx: " + tx);
println("tz: " + tz);
println("xC: " + xComp);
println("NewXC: " + newXComp);
println("zC: " + zComp);
println("NewZC: " + newZComp);
println("Angle: " +angle);*/
//--------------------------------------*/
}
if (abs(diffY) > stillBox)
ty += diffY/(sensitivity/1.5);
}
}
public void locationUpdate(){
/*Old method==================================
if(keyPressed){
if (keyCode == UP || key == 'w'){
z-=10;
tz-=10;
}
else if (keyCode == DOWN || key == 's'){
tz+=10;
z+=10;
}
else if (keyCode == LEFT || key == 'a' ){
tx-=10;
x-=10;
}
else if (keyCode == RIGHT || key == 'd'){
tx+=10;
x+=10;
}
}
============================================*/
//Apply Movement
if(moveMode == 1){
z += moveZ;
tz += moveZ;
x += moveX;
tx += moveX;
}
else if(moveMode == 2){
if(moveUP){
z += zComp/movementSpeed;
tz+= zComp/movementSpeed;
x += xComp/movementSpeed;
tx+= xComp/movementSpeed;
}
else if(moveDOWN){
z -= zComp/movementSpeed;
tz-= zComp/movementSpeed;
x -= xComp/movementSpeed;
tx-= xComp/movementSpeed;
}
if (moveRIGHT){
z += xComp/movementSpeed;
tz+= xComp/movementSpeed;
x -= zComp/movementSpeed;
tx-= zComp/movementSpeed;
}
if (moveLEFT){
z -= xComp/movementSpeed;
tz-= xComp/movementSpeed;
x += zComp/movementSpeed;
tx+= zComp/movementSpeed;
}
}
//New method also uses keyPressed() and keyReleased()
// Scroll Down!
}
public void jumpManager(int magnitude){
/*
if(keyPressed && key == ' ' && canJump){
vY -= magnitude;
if(vY < -20)
canJump = false;
}
else*/ if (y < ground+standHeight)
vY ++;
else if (y >= ground+standHeight){
vY = 0;
y = ground + standHeight;
}
if((!canJump) && (!keyPressed)){
//println("Jump Reset!");
canJump = true;
}
y += vY;
}
public void keyPressed(){
if(keyCode == UP || key == 'w'){
moveZ = -10;
moveUP = true;
}
else if(keyCode == DOWN || key == 's'){
moveZ = 10;
moveDOWN = true;
}
else if(keyCode == LEFT || key == 'a'){
moveX = -10;
moveLEFT = true;
}
else if(keyCode == RIGHT || key == 'd'){
moveX = 10;
moveRIGHT = true;
}
if(key == 'm' && m==1){
m=0;
}
else if(key == 'm' && m==0){
if(key == '1')
{
}
rotateY(180);
fill(#EAFF0F);
textSize(50);
text("menu", x-100, y, z+300);
m=1;
}
}
public void keyReleased(){
if(keyCode == UP || key == 'w'){
moveUP = false;
moveZ = 0;
}
else if(keyCode == DOWN || key == 's'){
moveDOWN = false;
moveZ = 0;
}
else if(keyCode == LEFT || key == 'a'){
moveLEFT = false;
moveX = 0;
}
else if(keyCode == RIGHT || key == 'd'){
moveRIGHT = false;
moveX = 0;
}
}
void mousePressed()
{
}
public float correctAngle(float xc, float zc){
float newAngle = -degrees(atan(xc/zc));
if (xComp > 0 && zComp > 0)
newAngle = (90 + newAngle)+90;
else if (xComp < 0 && zComp > 0)
newAngle = newAngle + 180;
else if (xComp < 0 && zComp < 0)
newAngle = (90+ newAngle) + 270;
return newAngle;
}
People can use their first person view to walk the library.It is fine in java mode,but when I put it in java script mode,the view has problem.So , which part of my code has problems so that it can not run on website?
Thank you very much.

Categories