我正在做一个射击游戏,用数组添加很多敌人,然后在地图上给他们一个随机位置,但我不知道如何在他们到达位置后让他们移动。这是我的敌人职业:
import com.badlogic.gdx.math.Vector2;
import java.util.Random;
public class Enemy {
private static final Random r = new Random();
int x = r.nextInt(36);
int y = r.nextInt(24);
Vector2 vect = new Vector2(x,y);
float ROTATION_SPEED = 500;
public Follower(float SPEED, float rotation, float width, float height,
Vector2 position) {
super(SPEED, rotation, width, height, position);
}
public void advance(float delta, Ship ship) {
if(rotation > 360)
rotation -= 360;
position.lerp(vect, delta);
rotation += delta * ROTATION_SPEED;
super.update(ship);
//Edited: i forget to put this lines:
if(vect.equals(this.getPosition())){
x = r.nextInt(36);
y = r.nextInt(24);
}
}
我应该在此类中实现什么样的方法来使它们在一定时间后移动 x/y 值?
当你在没有多线程的情况下使用 Thread.sleep 时,整个游戏将冻结。但是你也可以用定时器和定时器任务来解决它,这很容易,特别是对于初学者(你可以把它添加到你的代码之前(:
import java.util.Timer;
import java.util.TimerTask;
public class Enemy{
Timer t;
public Enemy(){ //in your constructor
t = new Timer();
t.scheduleAtFixedRate(new TimerTask(){
public void run(){
/*here the code for the movement, e.g:
x += 5;
y += 5;*/
}
}, delay, speed); //delay is after which time it should start usually delay is 0, speed is the time in ms e.g. 9
}
}
Thread.sleep 是在进行进一步处理之前睡眠一段时间的方式。您将很好地开始研究Java中的多线程,以轻松解决此类问题。你可以从这里开始:http://docs.oracle.com/javase/tutorial/essential/concurrency/
为了立即解决,只需在 while 循环中编写 Thread.sleep((。