[英]Making a bullet pass opposite sides of the screen
因此,對於編碼任務,我們必須進行坦克比賽。 我使用以下方法創建了子彈類:
package com.MyName.battletanks;
import com.badlogic.gdx.graphics.g2d.Sprite;
public class Bullet {
public Sprite b;
public float vx = 0;
public float vy = 0;
public Bullet(Sprite temp) { b = temp;}
public void move() { b.translate(vx*3,vy*3);}
}
我的變量如下:
Sprite Player1;
Sprite Player2;
ArrayList<Bullet> bullets;
單擊空格后,它將使用以下命令創建項目符號:
if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
Bullet bullet = new Bullet(new Sprite(new Texture("Bullet1.png")));
bullet.b.setPosition(Player1.getX() + Player1.getWidth() / 2, Player1.getY() + Player1.getHeight() / 2);
float rotation = (float) Math.toRadians(Player1.getRotation());
bullet.vx = (float) Math.cos(rotation);
bullet.vy = (float) Math.sin(rotation);
bullets.add(bullet);
}
現在,這是我的代碼,可讓我的坦克穿過屏幕的一側到達另一側:
if (Player1.getX() > Gdx.graphics.getWidth()){
Player1.setX(-64f);
} else if(Player1.getX()<-64f){
Player1.setX(Gdx.graphics.getWidth());
}
if (Player1.getY() > Gdx.graphics.getHeight()){
Player1.setY(-64);
} else if(Player1.getY() < -64f){
Player1.setY(Gdx.graphics.getHeight());
}
現在,播放器1是一個精靈,但是,項目符號是使用arraylist和自制項目符號類創建的。 結果,我無法使用對子彈頭所做的Player1的代碼。 所以,我的問題是,如何讓我的子彈傳遞到屏幕的另一側?
您可以使用模%
運算符執行%
操作:
bullet.position.x %= Gdx.graphics.getWidth();
bullet.position.y %= Gdx.graphics.getHeight();
這未經測試,但可以正常工作。 另外,我注意到您為速度使用了2個浮點,並且您確實應該使用Vector2
因為這樣您就可以輕松縮放和標准化它,這對速度很有用。
對於Player
類和Bullet
類而言,這實際上是相同的,因為您具有相同的屏幕空間,因此您可以通過將當前代碼轉換為帶有任何sprite的函數來重用當前代碼。 該功能的定義如下:
void fitOnScreen(Sprite sprite) {
if (sprite.getX() > Gdx.graphics.getWidth()){
sprite.setX(-64f);
} else if(sprite.getX()<-64f){
sprite.setX(Gdx.graphics.getWidth());
}
if (sprite.getY() > Gdx.graphics.getHeight()){
sprite.setY(-64);
} else if(sprite.getY() < -64f){
sprite.setY(Gdx.graphics.getHeight());
}
}
您可以在Player
上調用此函數,還可以遍歷每個項目符號,例如:
fitOnScreen(Player1);
for (Bullet b: bullets) fitOnScreen(b.b);
好吧,您要問的是如何遍歷項目符號的每個實例並更改其屬性。
我必須同意@Zac的算法對於一顆子彈可以正常工作,但是您需要將其放入循環中以遍歷每顆子彈才能生效。
這是您可以在游戲屏幕的render()方法中執行的操作的示例:
Iterator<Bullet> it = bullets.iterator();
while(it.hasNext()) {
Bullet bullet = it.next();
// Now you do the position correction
bullet.b.setPosition(bullet.b.getX()%Gdx.graphics.getWidth(), bullet.b.getY()%Gdx.graphics.getHeight());
}
當然,還有其他方法可以這樣做,但這可能是最簡單的方法。 您也可以在此循環中回收用於播放器的代碼。
另外,請注意,使用這種方法時,項目符號越多,應用程序就越拖延。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.