我希望为我的年终项目(在高中学习计算机科学)制作一个非常基本的游戏,但找不到任何关于如何使我正在绘制的矩形面对光标的答案。这个网站过去非常有用,但这是我的第一个问题,希望你们能提供帮助。
dir = Math.toRadians(Math.atan2(yy1,xx1)/2*Math.PI);
我假设这部分代码是问题所在,或者,
g2d.rotate(dir,xx,yy);
这个。我应该使用仿射变换吗?如果可以,如何使用?
提前致谢。
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) {
}
}