I'm hope to make a very basic game for my end of year project (going though computer science in high school) but cant find any answers as to how to make the rectangle I am drawing to face the cursor. This site has been very useful in the past but this is my first question and i hope you guys can help.
dir = Math.toRadians(Math.atan2(yy1,xx1)/2*Math.PI);
I'm presuming the either this peice of code that is the problem or,
g2d.rotate(dir,xx,yy);
This. Should I use affine transformation and if so how?
Thanks in advance.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*;
public class W extends Applet implements KeyListener, MouseMotionListener {
int xx=100,yy=100,xx1,yy1,wid,hig;
String key;
Rectangle rect1;
double dir, trueing=0;
Image offImage;
Graphics offGraphics;
public void init() {
setSize(800,600);
addKeyListener(this);
addMouseMotionListener(this);
}
public void update(Graphics g) {
if (offGraphics == null) {
offImage = createImage(800,600);
offGraphics = offImage.getGraphics();
}
offGraphics.setColor(Color.WHITE);
offGraphics.fillRect(0,0,800,600);
Graphics2D g2d = (Graphics2D)offGraphics;
offGraphics.setColor(Color.BLACK);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.rotate(dir,xx,yy);
g2d.draw(new Rectangle(xx, yy, 10, 10));
offGraphics.setColor(getForeground());
g.drawImage(offImage, 0, 0, this);
}
public void paint(Graphics g) {
update(g);
}
public void Game(){
}
public void keyPressed(KeyEvent ke){
if (ke.getKeyCode() == KeyEvent.VK_UP){
yy--;
key = "u";
System.out.println(key+xx+"-"+yy);
repaint();
}
if (ke.getKeyCode() == KeyEvent.VK_DOWN){
yy++;
key = "d";
System.out.println(key+xx+"-"+yy);
repaint();
}
if (ke.getKeyCode() == KeyEvent.VK_LEFT){
xx--;
key = "l";
System.out.println(key+xx+"-"+yy);
repaint();
}
if (ke.getKeyCode() == KeyEvent.VK_RIGHT){
xx++;
key = "r";
System.out.println(key+xx+"-"+yy);repaint();
repaint();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void mouseMoved(MouseEvent e) {
xx1=e.getX();
yy1=e.getY();
showStatus( "Mouse at (" + xx1 + "," + yy1 + ")" );
dir = Math.toRadians(Math.atan2(yy1,xx1)/2*Math.PI);
repaint();
}
public void mouseDragged(MouseEvent e) {
}
}