im creating a 2d game. i have an array of a bullet class which i use to create my bullets. i also have another array this consisting sprites which move around the screen this being rendered every 3 to 4 seconds.
Problem:
when the bullet and other sprite meet at the same location the bullet should be removed or deleted and never comeback.
please help me...
code for rendering bullet:
bullet.java:
import com.badlogic.gdx.math.Vector2;
public class Bullet{
public Vector2 bulletLocation = new Vector2(0, 0);
public Vector2 bulletVelocity = new Vector2(0, 0);
public Bullet(Vector2 sentLocation, Vector2 sentVelocity) {
bulletLocation = new Vector2(sentLocation.x, sentLocation.y);
bulletVelocity = new Vector2(sentVelocity.x, sentVelocity.y);
}
public void Update() {
bulletLocation.x += bulletVelocity.x;
bulletLocation.y += bulletVelocity.y;
}
}
main class:
ArrayList<Bullet> bulletManager = new ArrayList<Bullet>();
Array<Other> OthersManager = new Array<Other>();
Bullet currentbullet;
Other currentOthers;
render();
int other = 0;
while (other < OthersManager.size) {
currentOthers = OthersManager.get(other);
if (currentOthers.OtherLocation.x > guy.getX()) {
currentOthers.OtherVelocity.x = -2f;
}
if (currentOthers.OtherLocation.x < guy.getX()) {
currentOthers.OtherVelocity.x = 2f;
}
currentOthers.Update();
others.setPosition(currentOthers.OtherLocation.x,currentOthers.OtherLocation.y);
others.draw(batch);
other++;
}
int counter = 0;
while (counter < bulletManager.size()) {
currentbullet = bulletManager.get(counter);
currentbullet.Update();
shoot.setPosition(currentbullet.bulletLocation.x,currentbullet.bulletLocation.y);
if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
bulletManager.remove(currentbullet);
}
shoot.draw(batch);
counter++;
}
It seems that the problem is in this block of code:
if(currentOthers.OtherLocation.x == currentbullet.bulletLocation.x){
bulletManager.remove(currentbullet);
}
I would suggest you to use epsilonEquals method from Vector2 class to check whether your currentOthers.OtherLocation matches currentbullet.bulletLocation:
if(currentOthers.OtherLocation.epsilonEquals(currentbullet.bulletLocation)){
bulletManager.remove(currentbullet);
}
Moreover you can use epsilonEquals with float epsilon: documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.