2014-12-30 21 views
0

问题:因此,我创建了一个带有Window类的程序,该类创建了一个JFrame,并在其上添加了一个来自我的DrawStuff类的JPanel。 DrawStuff类创建一个(应该)在屏幕上弹跳的球,当它碰到JFrame边界时,改变方向。球移动,但由于某种原因,我的移动方法的checkbounds部分不起作用。任何帮助将不胜感激。我的目标是保持球的界限。从DrawStuff类为什么我的move()方法不让球保持边界?

代码:

public class Drawstuff extends JPanel { 
    private int x = 0; 
    private int y = 0; 
    private int dx, dy=0; 

    public Drawstuff(){ 
     x = 300; 
     y = 250; 
     dx = 0; 
     dy = 0; 
    } 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D) g; 
     this.setBackground(Color.BLACK); 
     g2d.setColor(Color.RED); 
     g2d.fillOval(x,y,50,50);  
    } 
    public void move(){ 

     if (x < 600){ 
      dx = 1; 
     } 
     if (y < 500){ 
      dy = 1; 
     } 
     if (x > 600){ 
      dx = -1; 
     } 
     if (y >500){ 
      dy = -1; 
     } 
     x += dx; 
     y += dy; 
    } 

} 

简单的 “GameLoop” 从窗口类(如果需要)

while (true){ 
      stuff.repaint(); 
      stuff.move(); 
      try { 
       Thread.sleep(5); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
+0

那么它目前做了什么?对不起,再次看到我的坏 –

+1

'if(x <600){}'???你不是指'如果(x <0)'?与“y”相同... – FoggyDay

+1

如果x == 600,您只是不动? –

回答

3

move是错误的。它的逻辑是错误的。你想让球弹起来,所以当它撞到墙上时,它的运动就会反转。你所做的是:如果是在室外进入室内,当进入室外时,更改为:

public void move(){ 
     if (x < 0) { // left bound 
      dx = 1; // now move right 
     } 
     if (y < 0){ // upper bound 
      dy = 1; // now move down 
     } 
     if (x > 600){// right bound 
      dx = -1; // now move left 
     } 
     if (y >500){ // lower bound 
      dy = -1; // now move up 
     } 
     x += dx; 
     y += dy; 
    } 

以备将来使用,我可以建议你做以下方式:

public void move(){ 
     if (x < 0) { // left bound 
      dx = -dx; // now move right, same speed 
      x=-x;  // bounce inside 
     } 
     if (y < 0){ // upper bound 
      dy = -dy; // now move down, same speed 
      y=-y;  // bounce inside 
     } 
     if (x > 600){  // right bound 
      dx = -dy;  // now move left, same speed 
      x=600-(x-600); // bounce inside 
     } 
     if (y >500){  // lower bound 
      dy = -dy;  // now move up, same speed 
      y=500-(y-500); // bounce inside 
     } 
     x += dx; 
     y += dy; 
    } 

所以,你现在可以使用你想要的(至少不无道理)任何矢量速度。矢量坐标与撞击相对应,并将球重新定位在边界内。

+0

感谢您的帮助。然而,在其中一位用户指出我的错误逻辑后,我将其改为上面的内容。出于某种原因,现在我的圈子根本不动? @ Jean-Baptiste – imgolden62

+0

不仅像素坐标,例如 - 1.Thread.sleep(5);在标准Native OS的延迟下,标准最小值应该是25-33,2.从Swing Timer调用Java6和更新版本,因为Thread.sleep(int);阻止一个EDT,更多在Oracle教程Concurncy in Swing – mKorbel

+0

@mKorbel我不确定我是否理解了你所说的所有内容,但是如果它有帮助,圆圈就会以适当的速度移动,移动逻辑处于我的发布移动方法中。然后,我只是改变了两个“雾天”提示的语句逻辑,现在我的圈子根本不动。有什么建议么? – imgolden62