Home » AS3, Game

Common mistakes when using hitTestPoint function of a DisplayObject

25 April 2009 6 Comments

hitTestPoint is a very usefull function when you want to test if a point (x, y) hits a shape, even an irregular one.

But there are a few but important things that you got to remember to get it to work properly:

  1. the dispay object you’re working on must be added to the display list.
  2. use TRUE for the last parameter of the function if you want your point to be tested against the actual shape and FALSE if you just need it to be checked against its bounding box.
  3. and last but not least, the coordinate space is the Stage’s one. So to get it right, simply use the localToGlobal function on the same display object you’re using the hitTestPoint function and you will get a point object containing the offset/difference for the x and y coordinate.
  4. Also check if your DisplayObject you want to test a point against is not being used as a mask.
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • E-mail this story to a friend!
  • LinkedIn
  • TwitThis

6 Comments »

  • Chris said:

    I have been looking for an answer to a bug I have in my game and number 3 was exactly what I needed to find. My hero would fall through the level because I started using a camera. The localToGlobal should fix that though, I think. Many thanks!

  • Kawika said:

    Thanks so much! #3 was exactly what I was looking for! How come no one TELLS you these things in the Flash documentation? I was ready to tear my hair out on a client project!

  • Gabriel said:

    From the Adobe documentation

    DisplayObject.hitPointTest()

    “Evaluates the display object to see if it overlaps or intersects with the point specified by the x and y parameters. The x and y parameters specify a point in the coordinate space of the Stage, not the display object container that contains the display object (unless that display object container is the Stage). ”

    Although a common mistake, it is there in the documentation in plain print.

  • tarun said:

    thanks!!
    #2 is very useful to me.
    Please send me some examples of #3 as its hard to understand.

  • Ryan said:

    Thanks, my problem was #3.

  • iguess said:

    thank you, valuable information^

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

Security Code: