我对此有疑问......当我画一条线时,角色跟随我画的线,但计算机在其他地方画了一条线:
那么有人知道发生了什么吗?
My code:
@SuppressWarnings({"serial","rawtypes","unchecked"})
public class someGame extends JFrame implements MouseListener, KeyListener{
ArrayList lines = new ArrayList();
Point2D.Double start;
final Color BROWN = new Color(156,93,82);
Slider thread;
Rectangle cow = null;
boolean drawGuy = false;
public someGame(){
super("Some Game");
setSize(700,700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
addKeyListener(this);
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
for(int i = 0; i < lines.size(); i++){
Line2D.Double temp = (Line2D.Double) lines.get(i);
int x1 = Integer.parseInt(""+Math.round(temp.getX1()));
int x2 = Integer.parseInt(""+Math.round(temp.getX2()));
int y1 = Integer.parseInt(""+Math.round(temp.getY1()));
int y2 = Integer.parseInt(""+Math.round(temp.getY2()));
g.drawLine(x1,x2,y1,y2);
}
if(drawGuy){
try{
URL url = this.getClass().getResource("resources/img/world/char.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
g.drawImage(image, cow.x, cow.y, this);
} catch(Exception exc){}
}
}
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){
start = new Point2D.Double(e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e){
Point2D.Double end = new Point2D.Double(e.getX(),e.getY());
lines.add(new Line2D.Double(start,end));
repaint();
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){
if(e.getKeyChar()=='p'||e.getKeyChar()=='P'){
thread = new Slider();
thread.start();
thread.action(true);
}
if(e.getKeyChar()=='q'||e.getKeyChar()=='Q'){
thread.action(false);
drawGuy = false;
thread = null;
}
}
private class Slider extends Thread{
double velocity, gravity;
boolean go = false;
public void run(){
if(go){
initGuy();
velocity = 0;
gravity = 1;
}
while(go){
try{
Line2D.Double lineTaken = null;
boolean onLine = false;
int firstOnLine = -1;
for(int i = lines.size()-1; i>=0; i--){
Line2D.Double temp = (Line2D.Double) lines.get(i);
if(temp.intersects(cow.x,cow.y,50,50)){
lineTaken = temp;
onLine = true;
if(firstOnLine!=i){
firstOnLine = i;
gravity = 0;
}
break;
}
}
if(onLine){
double grav = (lineTaken.y2-lineTaken.y1)/50;
double vlct = (lineTaken.x2-lineTaken.x1)/100;
if(velocity<5)velocity+=vlct;
if(gravity<2.5)gravity+=grav;
}
else{
gravity+=.2;
}
cow.x+=velocity;
cow.y+=gravity;
Thread.sleep(75);
repaint();
}catch(Exception e){break;}
}
}
public void action(boolean b){
go = b;
}
public void initGuy(){
Line2D.Double firstLine = (Line2D.Double) lines.get(0);
int x = Integer.parseInt(""+Math.round(firstLine.x1));
int y = Integer.parseInt(""+Math.round(firstLine.y1));
cow = new Rectangle(x+30,y-20,30,30);
drawGuy = true;
}
}
对不起大代码,但我不知道出了什么问题......非常感谢任何回答的人:)
......是的,主要方法是someGame g = new someGame();