7.17. Converting Between Coordinate Spaces

Problem

You want to convert between the movie clip’s coordinate space and the Stage’s coordinate space, or vice versa.

Solution

Create a point object and use localToGlobal( ) or globalToLocal( ).

Discussion

The most common reason for needing to convert coordinates from one coordinate space to another is to perform hit tests (see Recipe 7.15). But regardless of why you want to perform the coordinate conversions, you can quickly accomplish your task using the localToGlobal( ) and globalToLocal( ) methods. Each method requires you to first create a point object. A point object is an instance of the Object class with x and y properties set to the x and y coordinates of the point of interest.

You can define a point object using an object literal. For example:

pnts = {x: 24, y:42};

If the point object represents a point in the global coordinate system that you want to convert to the local equivalent, you should use the globalToLocal( ) method and invoke it from the target movie clip:

localMovieClip.globalToLocal(pnts);

If you want to convert a local point to a point in the global coordinate system, you should use the localToGlobal( ) method instead:

localMovieClip.localToGlobal(pnts);

See Also

Recipe 7.15

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.