ForumsProgramming ForumAbsolute coordinates

5 3721
Nodnarbisc
offline
Nodnarbisc
1 posts
Nomad

Hey all,
Say I have a movieclip of class "gun" nested inside a movieclip of class "hero". The gun fires a bullet of class "bullet". Now the problem is if in the gun class i say parent.addchild(newbullet) the bullet fires from the gun, but moves with the hero (like if the hero jumps the bullet jumps). If instead I say stage.addchild(newbullet), the bullet is fired from the upper left corner of the stage, but it moves independently of the hero. So, my question is, how do you reference the absolute coordinates of a nested movieclip? I want the bullet to be added to the stage so it moves independently of the hero, but it needs to be fired from the coordinates of the gun.

Any help would be appreciated.
Thanks.

  • 5 Replies
PixelSmash
offline
PixelSmash
566 posts
Nomad

I see you already found what's causing your problems, just not how to solve them. Took me quite some time to figure out as well, but your magic function is mc.localToGlobal(). Actually, to be precise try something like this:

private function fire():void{
//new bullet created as bullet_mc... that's your own code

}

PixelSmash
offline
PixelSmash
566 posts
Nomad

Wait, that's not exactly what I meant. Damn keyboard acting up... let me try again:

private function fire():void{
//new bullet created as bullet_mc... that's your own code
//don't forget to include Point!
var point:Point = new Point(0,0);
point = gun_mc.localToGlobal(point);
bullet_mc.x = point.x;
bullet_mc.y = point.y;
stage.addChild(bullet);
}

Now, it could well be that you want them to fire from some other point, but hey - I think you get the hang of it.
Do note that you need to think about which movieclip you use for your localToGlobal - different MCs lead to different outcomes!

Good luck!

Marcellino
offline
Marcellino
5 posts
Nomad

I've had numerous problems like this as well. Here's the part that I try to keep in mind:

Let's say you have a "Hero" class, which contains a variable that represents the actual Sprite "HeroSymbol." When you add HeroSymbol to the stage, it has an x and y coordinate set that is different from the instance of the class itself, "Hero." Therefore, saying myHero.x may return a completely different value than myHero.theHeroSymbol.x, it all depends on what variables you're manipulating to actually move the character. This goes for other classes as well. So, for example, if you're moving your bullets via their SYMBOL's x and y but moving your hero via the CLASS's x and y, you'll probably run into hit detection errors. Hope this was helpful! Good luck!

rjbman
offline
rjbman
215 posts
Nomad

do something like:

private function fire(x:number, y:number):void{

bullet=new Bullet;
bullet.x=x;
bullet.y=y;
stage.addChild(bullet);
}

Then when you call fire, just give it the gun x and y coordinates. Like: fire(gun.x,gun.y);

Showing 1-4 of 5