Java非静态变量
我正在尝试使用两个球精灵创建球碰撞。当一个球碰撞时,它的速度应该取决于其他球的初始速度,因此在精灵中我需要调用其他球的速度,但我不知道如何通过非静态变量消息。这是有错误的那一行Java非静态变量,java,static,non-static,Java,Static,Non Static,我正在尝试使用两个球精灵创建球碰撞。当一个球碰撞时,它的速度应该取决于其他球的初始速度,因此在精灵中我需要调用其他球的速度,但我不知道如何通过非静态变量消息。这是有错误的那一行 xa = BIGBALLspeedx()*(BIGBALLmass()-1)+(BallTest.ball.BALLspeedx()*2*1); 这是我的一个精灵和主包“BallTest”的代码: package balltest; import java.awt.Graphics2D; import java.aw
xa = BIGBALLspeedx()*(BIGBALLmass()-1)+(BallTest.ball.BALLspeedx()*2*1);
这是我的一个精灵和主包“BallTest”的代码:
package balltest;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import static java.lang.Math.sqrt;
public class BigBall {
private final int DIAMETER = 80;
int x = (int )(Math.random() * 200 + 15 );
int y = (int )(Math.random() * 200 + 15 );
int xa = (int )(Math.random() * 4 );
int ya = (int )(1 );
private BallTest game;
public BigBall(BallTest game) {
this.game= game;
}
public void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
ya=-1;
if (y + ya < 1)
ya=1;
if (50>sqrt(xDIFF()*xDIFF()+yDIFF()*yDIFF()) && -50<sqrt(xDIFF()*xDIFF()+yDIFF()*yDIFF())) {
xa = BIGBALLspeedx()*(BIGBALLmass()-1)+(BallTest.ball.BALLspeedx()*2*1);
}
x = x + xa;
y = y + ya;
}
public int BIGBALLx() {
return x+40;
}
public int BIGBALLy(){
return y+40;
}
public int BIGBALLspeedx(){
return xa;
}
public int BIGBALLspeedy(){
return ya;
}
public int BIGBALLmass(){
return 5;
}
public int xDIFF(){
return game.ball.BALLx()-game.BigBall.BIGBALLx();
}
public int yDIFF(){
return game.ball.BALLy()-game.BigBall.BIGBALLy();
}
public void paint2(Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
您正在尝试引用BallTest.ball-BallTest可能是另一个类,而ball是该类中定义的实例变量。在Java术语中,BallTest是一个静态引用,它引用一个类,而不是一个对象,而ball只定义了BallTest的一个实例 在代码的其他部分中,您将引用game.ball。如果看不到代码的其余部分,就无法确定,但是您应该使用game.ball而不是BallTest.ball吗 就是应该是这样吗?
xa = BIGBALLspeedx()*(BIGBALLmass()-1)+(game.ball.BALLspeedx()*2*1);
错误是什么?你到底遇到了什么问题?非静态球不能从静态上下文中引用你还没有向我们展示BallTest类,但我会大胆猜测它没有静态场球。当然,它会抛出这个错误。您的变量称为game,因此应为game.ball.BALLspeedx。您还应该阅读Java.cheers epicandaforce中的命名约定!!
xa = BIGBALLspeedx()*(BIGBALLmass()-1)+(game.ball.BALLspeedx()*2*1);