我正在用java制作汽车游戏。道路的速度是在主方法中设定的,但我需要更新速度(汽车越界并被草减速)。
这是我想要控制速度的int的部分改变了。
if(collision[12] > x)
{
roadSpeed = 150;
System.out.println("outside");
}
else
{
System.out.println("inside");
roadSpeed = 100;
}
这是我需要更新的主要方法。
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
final TestRoad road = new TestRoad();
road.timer.setDelay(roadSpeed);
更改int后,main方法不会更新定时器延迟。 我看过changelisteners但我不想要任何按钮或滑块。
如果被称为
,则声明为intpublic Boolean start = true;
public int i;
public int x;
public int y;
public int z;
public static int roadSpeed = 100; //<<<<<<<<<<declared here
public int lcolPoint = 0;
public int rcolPoint = 0;
public int colSlot = 0;
public int colOffset = 0;
public int carY;
public int[] collision;
public int[] colBuffer;
private BufferedImage carImg;
private Boolean right=false;
private Boolean left=false;
private Boolean first=true;
public TestRoad(){
this.setFocusable(true);
addKeyListener(this); //THIS IS ADDING THE KEYLISTENER
Color colors = new Color(51,102,0);
setBackground(colors);
//uses setPreferredSize instead of setSize because parent component utilizes a layout manager.
setPreferredSize(new Dimension(500, 500));
collision = new int[500];
colBuffer = new int[2];
for(int i=0; i<500; i++){
collision[i] = 0;
}
timer = new javax.swing.Timer(25, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addPoint();
carMove(); //<<<<< called here
repaint();
}
});
carmove -
public void carMove()
{
if(right==true)
x+=8;
if(left==true)
x-=8;
colBuffer[0] = collision[1];
collision[1] = lcolPoint;
collision[colSlot] = lcolPoint;
for(int z=2; z<21; z++){
colBuffer[1] = collision[z];
collision[z] = colBuffer[0];
colBuffer[0] = colBuffer[1];
}
if(collision[12] > x)
{
roadSpeed = 100;
System.out.println("outside");
}
else
{
System.out.println("inside");
roadSpeed = 50;
}
}
答案 0 :(得分:1)
roadSpeed
被宣布的位置,也无法了解其范围。
但是,让我们说它就是这样的
class Game {
private int roadSpeed = 200 ; // just an initial value
public void getSpeed(int collision, int roadSpeed){
if(collision[12] > x){
roadSpeed = 150;
System.out.println("outside");
} else {
System.out.println("inside");
roadSpeed = 100;
}
return;
}
public static void main(String[] args){
// do something that sets collision
getSpeed(collision, roadSpeed);
// and on with your code
在此代码中,您认为您正在设置roadSpeed
,但它是内部 roadSpeed
,而不是成员变量
因此,如果这没有帮助,您将不得不包含更多提示。