移动用java形状 [英] moving shapes with java
问题描述
我想创建一个Java方法,移动(),这将改变我的对象的位置(这是一个椭圆形)。我的椭圆有一个初始的x,y位置,所以我想通过调用JComponent的下面的方法将它移动从而沿JFrame。
公共类ShapeAnimation扩展形状{ 公共无效移动(){
xVel =(INT)(的Math.random()* 11);
yVel =(INT)(的Math.random()* 11); X = xVel + X;
Y = yVel + Y;
如果(X> this.x)
xVel = xVel * -1;
如果(Y> this.y)
yVel = yVel * -1;
}
}
您使用的是x变量在 X = xVel + X;
,但它不是在函数中声明,所以Java假设它是 this.x
所以你的code是这样的:
this.x = xVel + this.x;
this.y = yVel + this.y;
如果(this.x> this.x)//始终为假
xVel = xVel * -1;
如果(this.y> this.y)//始终为假
yVel = yVel * -1;
您需要将其更改为:
INT下一页末= xVel + this.x;
INT newy指定= yVel + this.y;
如果((下一页末℃,)||(下一页末> this.maxX))
xVel = xVel * -1;
其他
this.x =下一页末;
如果((newy指定℃,)||(newy指定> this.maxY))
yVel = yVel * -1;
其他
this.y = newy指定;
MAXX和MAXY应该有其中x最大值和y可以有
请注意 - 这code在某些迭代不动的对象,用于教学目的,我建议你更新了这样的情况。
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;
}
}
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
这篇关于移动用java形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!