为什么这个点会改变?

时间:2016-09-26 05:14:59

标签: java 2d point

我试图限制某个单元格可以去的区域,所以我添加了一个Point spawn,这样我可以使用spawn.distance()来确保它不会偏离它的产生太远。问题是它不断变化到单元格的当前位置。据我所知,在设置后没有任何改变它。有没有人看到它正在改变的原因?

实体类:

public abstract class Entity {

    protected int width, height;

    protected Point location;
    protected CellType cellType;

    abstract void tick();
    abstract void render(Graphics g);

    public int getWidth() {
        return width;
    }
    public int getHeight() {
        return height;
    }
    public Point getLocation() {
        return location;
    }
    public CellType getCellType() {
        return cellType;
    }

}

细胞分类:

public class Cell extends Entity{

    private Random random;

    private CellType cellType;
    private Point spawn;

    private int angle;
    private float xVelocity, yVelocity;
    private float maxVelocity = .2f;

    public Cell(Point location) {
        random = new Random();

        cellType = MasterGame.cellTypes.get(random.nextInt(MasterGame.cellTypes.size()));
        width = MasterGame.cellSizes.get(cellType);
        height = width;
        spawn = location;
        super.location = location;
    }

    int ticks = 0;
    public void tick() {
        if(ticks == 15) {
            System.out.println(spawn);
            angle = random.nextInt(360);
            xVelocity = (float) (maxVelocity * Math.cos(angle));
            yVelocity = (float) (maxVelocity * Math.sin(angle));
            ticks = 0;
        } 
        if(ticks % 3 == 0){
            location.x += xVelocity;
            location.y += yVelocity;
        }
        ticks++;
    }

    public void render(Graphics g) {
        g.setColor(Color.DARK_GRAY);
        g.fillOval(location.x, location.y, width, height);
        g.setColor(Color.GREEN);
        g.fillOval((int)(location.x+(width*.125)), (int)(location.y+(height*.125)), (int)(width*.75), (int)(height*.75));
    }

}

1 个答案:

答案 0 :(得分:0)

   spawn = location;
   super.location = location;

您有两个引用一个对象的变量。使用某种复制构造函数或类似方法将原始位置存储为spawn