Understanding AS3 localToGlobal method

One AS3 DisplayObject method I don’t see that much used since AS2 became obsolete is localToGlobal.

Now I’ll show you how useful can be this method when it’s time to save coding time.

First, the definition:

localToGlobal(point:Point):Point
Converts the point object from the display object’s (local) coordinates to the Stage (global) coordinates.

Let’s see what does it mean.

We have a square, whose width (and height) is 60 pixels.

Assuming its center is at (0,0), we can easily determine the coordinates of the four vertexs since if the width is 60, the half-width will be 30.

The diagonal, useful during the script you’re about to see, is dermined by:

square_root(60*60+60*60) or square_root(2)*60

Now imagine to rotate clockwise the square by an arbitrary angle, and tell me the position of the upper left vertex.

You can do it with trigonometry this way:

x = -42.426*cos(45-angle) = -30 if angle is zero. (42.426 is half the diagonal)
y = -42.426*sin(45-angle) = -30 if angle is zero

It’s not impossible, but it can be done in an easier way using localToGlobal.

Basically we know the upper left vertex is always at (-30,-30) in a world relative just the square itself, no matter of its position in the stage.

localToGlobal will handle the position in the stage according to the absolute (-30,-30) coordinate.

Here it is the script:

package {
	import flash.display.Sprite;
	import flash.geom.Point;
	public class square_mc extends Sprite {
		public var diagonal:Number=42.42640687119285;
		public var deg_to_rad:Number=0.0174532925;
		public var point:Point;
		public var pos_x,pos_y:Number;
		public function square_mc():void {

		}
		public function random_pos():void {
			x=Math.random()*400+50;
			y=Math.random()*300+50;
			rotation=Math.random()*360;
			point=new Point(-30,-30);
			point=localToGlobal(point);
			pos_x=x+diagonal*Math.cos((135-rotation)*deg_to_rad);
			pos_y=y-diagonal*Math.sin((135-rotation)*deg_to_rad);
		}
	}
}

Line 5: defining the half diagonal of a square whose width is 30

Line 6: degrees to radians conversion number

Line 7: defining a Point variable. The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.

Lines 9-11: intentionally left blank for a possible more complex example in the future

Lines 13-15: randomly placing and rotating the square on the stage

Lines 16-17: retrieving upper left vertex coordinates using localToGlobal

Lines 18-19: retrieving upper left vertex coordinates using trigonometry

Here it is the result (included in a main class that just handles input and output)

Click the mouse on the stage to randomly move the square and retrieve the upper left vertex (marked in red) using both ways.

Which one do you prefer?

Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers