How do I change the x & y values of an instance?


(Jacob) #1

I’ve scoured through all the help topics and tutorials but can’t seem to find the answer. It feels like I’m missing something very fundamental here. I have an entity MyBlock with assigned x & y values (let’s say: x = 10; y = 10;) in it’s added() function. When I instantiate MyBlock and add it to the world, it adds where it should. However, I’m trying to create extra instances of it & have them add at different coordinates. So I’ll do this: public var myBlockInstance2:MyBlock = new MyBlock(); myBlockInstance2.x = 100; myBlockInstance2.y = 100. But when I add myBlockInstance2 to the world it just shows up at the 10, 10 coordinates. Please help.


(Jacob Albano) #2

When an entity is added to the world, its added() function is called. Regardless of what you might have set x and y, they will always be set to 10 when the entity is added because of what you have in its added() function.

You don’t have to set the position variables in added(), you know. You can set them at any time and the positions will be used when it’s added to the world.


(Jacob) #3

Thank you very much for your help. I knew that’s how the added() function behaves but wasn’t 100% sure so this clears that up. I had tried a few different things; like, assigning the x and y values in the constructor and messing around with a custom function in the class but kept getting errors or the entity just wouldn’t show up. I have now found something that works: I created a custom function setup() in the class, assigned values to x and y in there, and then called setup(); in the class’ constructor. Now when i: myBlockInstance2.x = 100;, the instance actually shows up at 100 instead of 10. Again, thank you for your help.


(Zachary Lewis) #4

The function declaration for Entity already supports placement, among other things.

public function Entity(x:Number = 0, y:Number = 0, graphic:Graphic = null, mask:Mask = null)

You can use this to create a Block class that will allow you to set the location.

public class Block extends Entity
{
  public function Block(x:Number = 0, y:Number = 0)
  {
    type = "block";
    super(x, y, new Image(BLOCK_IMAGE));
  }
}

With that, you can create blocks with reckless abandon!

add(new Block(100, 200));
add(new Block());
add(new Block(Math.random() * 1000, Math.random() * 1000);