2016-04-15 69 views
0

因此,对于编码分配,我们必须制作坦克游戏。让子弹通过屏幕的两侧

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是精灵,但是,子弹是使用数组列表和自制子弹类创建的。因此,我不能使用我为子弹做的Player1代码。所以,我的问题是,我怎样才能让我的子弹通过屏幕的另一端?

回答

1

可以使用模%运营商做这样的事情:

bullet.position.x %= Gdx.graphics.getWidth(); 
bullet.position.y %= Gdx.graphics.getHeight(); 

这不是测试,但它应该工作。另外,我注意到你正在使用2个浮标作为你的速度,你应该真的使用Vector2,因为那样你可以很容易地对它进行缩放和标准化,这对速度很有用。

+0

无论我放在哪里,bullet.x中的x都显示为红色,并且它一直给我一个错误。不太确定该怎么做。然而,vector2确实工作得很好。 –

+1

@LucasZ这是因为你没有在你的Bullet Class中写入变量x和y!你的位置在Sprite中。因此,你应该做'bullet.b.setPosition(bullet.b.getX()%Gdx.graphics.getWidth(),bullet.b.getY()%Gdx.graphics.getHeight());' – Fish

+0

如果这工作对你来说,你能接受它作为答案吗? :) – Zac

0

对于Player类和Bullet类来说,它们确实是一样的,因为您拥有相同的屏幕空间,因此您可以通过将当前代码变成一个接受任何精灵的函数来重用当前代码。

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); 
0

嘛,你问的是如何能该功能将被定义如下你贯穿子弹的每个实例并改变它们的属性。

我必须同意@ Zac的算法对于一颗子弹可以很好地工作,但是您需要将它放在一个循环中,才能通过每一颗子弹才能有效。

这里是你可以在你的渲染()你的游戏画面的方法做一个例子:

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()); 
} 

当然也有这样做的其他方式,但是这可能是最简单的方法。您也可以在此循环中回收您用于播放器的代码。

此外,请注意,使用此方法,项目符号越多,应用程序变得越迟缓。