[英]How can I delay each bullet? (Java -Slick2d - Game)
(事件偵聽器在另一個類中)當Game.render = true時,我會得到源源不斷的子彈,這些子彈看起來更像激光束,我希望兩者之間存在間隙。 我的意思是,我希望生成子彈,就像從機槍發射子彈一樣。 我知道我應該添加一些時間,但是我不確定該怎么做才能獲得想要的效果。 任何幫助將不勝感激,因為我一直在努力使其工作約一個小時。
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
public class Bullet {
// ArrayList
@SuppressWarnings("unchecked")
static ArrayList<Bullet> arrL = new ArrayList();
public Bullet(int x , int y) throws SlickException{
}
public static void update(GameContainer gc, int u) throws SlickException{
// when the left mouse button is clicked Game.fire = true, the key listener is in another class
if(Game.fire){
Bullet b = new Bullet(5,5);
arrL.add(b);
reloaded = false;
} if(!reloaded){
}
}
public static void renderBullets(GameContainer gc, Graphics g, int x, int y) {
// draws a new bullet for every 'bullet object' in the ArrayList called arrL
for(Bullet b : arrL){
g.drawRect(x,y,10,10);
x++;
}
}
}
在這種情況下,我最常做的事情是添加一個時間變量,該變量會從每次更新中減去增量(您具有u的變量),直到其降至0以下,此時我將其重置:
// Set this to whatever feels right for the effect you're trying to achieve.
// A larger number will mean a longer delay.
private static int default_bullet_delay = 500;
private static int time = 0;
public static void update (GameContainer gc, int u) throws SlickException {
time -= u;
if (time <= 0 && Game.fire) {
fireBullet(); // Replace this with your code for firing the bullet
time = default_bullet_delay; // Reset the timer
}
// The rest of the update loop...
}
基本上,即使Game.fire是true,在計時器倒數之前,子彈也不會發射。 一旦發生這種情況,便會設置計時器,直到下一次計時器倒數,下一顆子彈才能發射。 如果將其設置為合理的較小值,則每個項目符號之間應存在一定的距離。
這就是我這樣做的方式:
boolean reloaded = false; // Start with a reload becouse weapon not reload itself
float reloadTime = 100; // This is the "timer" (the value doesnt matter)
float startReloadTime = 100; // This is the actual reload time
private void shoot(int delta, float screenWidth, float screenHeight) {
// reload if not reloaded
if (!reloaded) {
reloadTime -= 0.5f * delta; // As I said, this is the timer
// If the reload finished, set the timer back to the reload time
if (reloadTime <= 0) {
reloaded = true; // reloaded, we can shoot
reloadTime = startReloadTime;
}
}
// Shoot only if reloaded
if (reloaded) {
// This is some direction calculating, ignore for now
float mouseWorldX = (x + (mouseX - screenWidth / 2));
float mouseWorldY = (y + (mouseY - screenHeight / 2));
float randomX = (float) Math.random() * (2000 / mouseWorldX);
float randomY = (float) Math.random() * (2000 / mouseWorldY);
mouseWorldX += randomX;
mouseWorldY += randomY;
// Add a new bullet element to the world (where will be rendered)
world.add(new Shot(world, camera, x + width / 2, y + height / 2, mouseWorldX - 2.5f, mouseWorldY - 2.5f, 5, 5, new Color(1, 0, 0, 1f)));
// We need to reload
reloaded = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.