java - A new object seems to change the fields of previous objects -
i'm writing game contains elevators obstacle. elevator spawns either left or right of screen , has random chance ascending elevator or descending elevator. looks this:
public class elevator extends worldobject { public static boolean ascending; public elevator(int screenheight, int xpos) { super(xpos, screenheight, 0, 0); ascending = new random().nextboolean(); } static public boolean isascending(){ return ascending; } }
worldobject extends looks this:
public class worldobject { protected float posx; protected float posy; protected float velx, vely; public float getposx() { return posx; } public void setposx(float posx) { this.posx = posx; } public float getposy() { return posy; } public void setposy(float posy) { this.posy = posy; } public float getvelx() { return velx; } public void setvelx(float velx) { this.velx = velx; } public float getvely() { return vely; } public void setvely(float vely) { this.vely = vely; } public worldobject(float posx, float posy, float velx, float vely) { this.posx = posx; this.posy = posy; this.velx = velx; this.vely = vely; } }
every 5 seconds elevator created , added arraylist of elevator
s so:
if (timetoelevator > 5.0f) { timetoelevator = 0; elevator elevator = new elevator((int) screenheight, (int) generateelevatorxpos()); sprite esprite = new sprite(elevatortexture); esprite.setorigin(0, 0); elevators.add(elevator); elevatorsprites.add(esprite); }
i check collisions in each elevator player, remove if goes out of bounds , if neither of these happen update position of elevator object:
public static void calculateelevatorcollisions() { int counter = 0; (iterator<elevator> = elevators.iterator(); i.hasnext(); ) { elevator item = i.next(); if (item.getposy() < -100) { //remove elevator } else if (..collision..) { //collision } else { item.setvely(item.isascending() ? -5 : 5); item.setposy(item.getvely() + item.getposy()); elevatorsprites.get(counter).setposition(item.getposx(), item.getposy()); counter++; }
my issue whenever new elevator
created current elevator
s change direction direction of new elevator
. suppose have 2 ascending elevators being drawn, whenever third elevator created descending, other 2 ascending elevators ascend!
what's causing this?
this problem:
public static boolean ascending; ^^^^^^
static
means "this class field shared objects". if changed field 1 object, noticed across all objects of type.
removing make ascending
instance field means each instance of elevator
have own copy can modify without changing other instances' copy.
Comments
Post a Comment