I am making a simple game where there's an object (a square with a rectangular barrel) that looks towards the mouse. The rotation part works pretty well, but I want the object to move when a button is pressed along the y axis, but directly upwards, not relative to its rotation. Now, when a button is pressed, the object moves forward in the direction it is facing. How is it possible to move it directly up the y axis, regardless of what direction the object is in? Here's the code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RotationTestMain extends JFrame implements MouseMotionListener, KeyListener{
public static final long serialVersionUID = 666L;
public static final int SIZE = 50;
double xComponent;
double yComponent;
Image dbImage;
Graphics dbg;
int x;
int y;
int centerX;
int centerY;
JPanel area;
public RotationTestMain(){
area = new JPanel();
area.addMouseMotionListener(this);
addKeyListener(this);
x = 487;
y = 359;
centerX = x + SIZE/2;
centerY = y + SIZE/2;
add(area);
setSize(1024,768);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g){
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
Graphics2D g2d = (Graphics2D) dbg;
draw(g2d);
g.drawImage(dbImage, 0, 0, this);
}
public void draw(Graphics2D g2d){
g2d.setColor(Color.BLACK);
g2d.rotate(calculateRotation(), centerX, centerY);
g2d.fillRect(x, y, SIZE, SIZE);
g2d.fillRect(centerX-5,y-20,10,25);
repaint();
}
public double calculateRotation(){
double rot;
if(yComponent >= 0){
rot = 3 * Math.PI - Math.atan(xComponent/yComponent);
}else {
rot = 2 * Math.PI - Math.atan(xComponent/yComponent);
}
return rot;
}
public static void main(String[] args) {
new RotationTestMain();
}
@Override
public void mouseDragged(MouseEvent m) {
centerX = x + SIZE/2;
centerY = y + SIZE/2;
xComponent = m.getX() - centerX;
yComponent = m.getY() - centerY;
}
@Override
public void mouseMoved(MouseEvent m) {
centerX = x + SIZE/2;
centerY = y + SIZE/2;
xComponent = m.getX() - centerX;
yComponent = m.getY() - centerY;
}
@Override
public void keyPressed(KeyEvent arg0) {
//TODO FIX THE MOVING PROBLEM
this.y -= 3;
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
}
Thanks so much for the help!!