改变形状不起作用的方法

时间:2011-10-05 23:14:22

标签: java

问题是根据我自己的设计的一些标准让我的形状随时间变化,因此我试图使形状改变大小,因为它碰到某些坐标但它会变成线并继续移动,因为下面的线是我的移动方法使我的形状移动,反弹,并水平和垂直移动。

public void move() {
    // Rebound X
    if (x <= 0 || x >= 400 - width) {
        moveX = moveX * -1;
    }

    // Rebound Y
    if (y <= 0 || y >= 400 - height) {
        moveY = moveY * -1;
    }

    // Wide shapes move up and down, narrow shapes move sideways
    if (width > 15) {
        y += moveY;
    } else {
        x += moveX;
    }

    // Change shape size
    if (y <= 100 || y >= 300 - height) {
        moveX = -moveX;
        height += height * 1 / 2;
    }

    //if {
    //    height -= height * 1/2;
    //    moveX = -moveX;
    //}

    //if (x < 20) {
    //    width -= width * 1/2;
    //    moveY = -moveY;
    //} else {
    //    width += width * 1/2;
    //    moveY = -moveY;
    //}
}

这是我所有形状扩展的形状类:

package shapes;

import java.awt.*;
import java.util.Random;

public abstract class Shape {
    protected int x;
    protected int y;
    protected int width;
    protected int height;
    protected Color color;
    protected int moveX = 1;
    protected int moveY = 1;

    public Shape() {
        Random r = new Random();
        width = r.nextInt(30) + 10;
        height = width;
        x = r.nextInt(400 - width);
        y = r.nextInt(400 - height);
        color = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
    }

    // Returns random value within range (low < n <= high).
    public int randomRange(int low, int high) {
        Random generator = new Random();
        return generator.nextInt(high - low + 1) + low;
    }

    public abstract void display(Graphics page);
    public abstract void move();
}

1 个答案:

答案 0 :(得分:1)

你的高度在几何上增长到非常大的值。要了解原因,请让您的程序告诉您发生了什么。使用println'ss或printf来显示程序状态。例如,您可以像这样使用Shape派生类:

public class MyShape extends Shape {
   private String name;
   private static int shapeCount = 1;

   public MyShape() {
      name = "Shape " + shapeCount;
      shapeCount++;
   }

   @Override
   public void display(Graphics page) {
      page.setColor(color);
      page.fillOval(x, y, width, height);
   }

   @Override
   public void move() {
      System.out.printf("%s: [x: %d, y: %d, w: %d, h: %d, mX: %d, my: %d]%n", 
            name, x, y, width, height, moveX, moveY);
      // Rebound X
      if (x <= 0 || x >= 400 - width) {
         moveX = moveX * -1;
      }

      // ... etc...