moving shapes with java

2019-03-06 22:25发布

I am trying to create a java method, move() that will change the location of my object (which is an ellipse). my ellipse has an initial x,y position so I'd like to move it along the Jframe by calling the following method from the JComponent.

public class ShapeAnimation extends Shape {

    public void move() {
        xVel=(int)(Math.random()*11);
        yVel=(int)(Math.random()*11);

        x=xVel+x;
        y=yVel+y;
        if(x>this.x)
            xVel=xVel*-1;
        if(y>this.y)
            yVel=yVel*-1;
    }
} 

1条回答
一夜七次
2楼-- · 2019-03-06 23:08

you are using x variable in x=xVel+x; but it is not declared in function, so java assumes it is this.x

so your code looks like this:

this.x=xVel+this.x;
this.y=yVel+this.y;
if(this.x>this.x) // always false
    xVel=xVel*-1;
if(this.y>this.y) // always false
    yVel=yVel*-1;

you need to change it to:

int newX = xVel+this.x;
int newY = yVel+this.y;
if( (newX<0) || (newX>this.maxX) )
    xVel=xVel*-1;
else
    this.x = newX;
if( (newY<0) || (newY>this.maxY) )
    yVel=yVel*-1;
else
    this.y = newY;

maxX and maxY should have maximum values which x and y can have

NOTE - this code do not move object during some iterations, for teaching purposes I suggest you to update it for such cases

查看更多
登录 后发表回答