使用Java 2D游戏。
精灵应该以特定的角度移动,按左右键设置,按下向上箭头键。
它不会以我希望它移动的角度移动。它以90度的角度移动,看起来不同。怎么了?
Thing
class
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.ImageIcon;
public class Thing {
Image image;
int width,height;
double x,y,dx,dy,angle;
public Thing(){
image = new ImageIcon(this.getClass().getResource("image.png")).getImage();
width = image.getWidth(null);
height = image.getHeight(null);
dx = 0;
dy = 0;
angle=90;
x = 250;
y = 250;
}
public void move(){
x += dx;
y += dy;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key==KeyEvent.VK_LEFT)angle-=5;
if(key==KeyEvent.VK_RIGHT)angle+=5;
if(key==KeyEvent.VK_UP){
dy = 5 * Math.sin(angle);
dx = 5 * Math.sin(90-angle);
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key==KeyEvent.VK_UP){
setDY(0);
setDX(0);
}
}
}
董事会类的相关方法:
package learningMovement;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener, KeyListener {
Thing t;
Timer timer;
public Board(){
timer = new Timer(10,this);
t = new Thing();
setFocusable(true);
timer.start();
addKeyListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(t.getAngle()),t.getX()+(t.getWidth()/2),t.getY()+(t.getHeight()/2));
g2d.drawImage(t.getImage(),(int)t.getX(),(int)t.getY(),this);
}
public void actionPerformed(ActionEvent e){
t.move();
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_LEFT)t.keyPressed(e);
if(key==KeyEvent.VK_RIGHT)t.keyPressed(e);
if(key==KeyEvent.VK_UP)t.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_LEFT)t.keyReleased(e);
if(key==KeyEvent.VK_RIGHT)t.keyReleased(e);
if(key==KeyEvent.VK_UP)t.keyReleased(e);
}
public void keyTyped(KeyEvent arg0) {}
}
答案 0 :(得分:1)
您的angle
是度,然后是
Math.sin(angle);
应该成为
Math.sin(Math.toRadians(angle));
因为罪的论证必须以弧度表示。
答案 1 :(得分:1)
为什么:
dy = 5 * Math.sin(angle);
dx = 5 * Math.sin(90-angle);
应该是:
dy = 5 * Math.sin(angle);
dx = 5 * Math.cos(angle);
同样喜欢HAL9000说不要忘记转换为弧度。