Reputation: 3
I have an ArrayList of the Class ZombieSprite
in my GameView
class which includes all my ZombieSprites
. In my ZombieSprite
class i have the method getDirection()
. Now i dont want the ZombieSprites
to collide. So need to check if the variable x
of the object thezombiesprite
id the ArrayList
is equal to any other variable x
of an object thezombiesprite
in the ArrayList
.
public class GameView extends SurfaceView {
// not interesting
List<ZombieSprite> zombieSpriteList = new ArrayList<ZombieSprite>();
// not interesting
public class ZombieSprite {
private int x = 0;
private int y = 0;
private void getDirection() {
if (x < PlayerSprite.x) {
x = x + xSpeed;
}
if (x > PlayerSprite.x) {
x = x - xSpeed;
}
if (x == PlayerSprite.x) {
x = x;
}
if (y < PlayerSprite.y) {
y = y + ySpeed + backgroundspeed;
}
if (y > PlayerSprite.y) {
y = y - ySpeed + backgroundspeed;
}
if (y == PlayerSprite.y) {
y = y + backgroundspeed;
}
}
I tried it with including following code into the getDireciton() method and added the ArrayList zombieSpriteList into the ZombieSprite class, too.
theGameView.getZombieSpriteList();
theGameView.zombieSpriteList = zombieSpriteList;
for (ZombieSprite thezombiesprite : zombieSpriteList) {
}
Upvotes: 0
Views: 631
Reputation: 2854
I think you need to check both x
and y
. What you can do is create a two-dimensional array that represents your N x M grid
. The indices of the array are the x
, y
coordinates. So when a zombie moves, check if grid[x,y]
is occupied. If it is not, mark that space and remove the previous grid[x,y]
value.
Upvotes: 1
Reputation: 368
You can override the method equal(Object obj) .
public boolean equals(Object o) {
if(o instanceof ZombieSprite)
return ((ZombieSprite)o).x == this.x;
return super.equals(o);
}
Then if you want to check if a zoombiesprite exists in theGameView.zombieSpriteList or not ( by x value)
theGameView.zombieSpriteList.contains(...)
Upvotes: 2