views:

557

answers:

2

I there a way to "detect" if a particular sprite is within the viewable area of a scrollRect?

I have a list of thumbnails in a scrollRect and I only want to load images for these thumbnails if and when the thumbnail sprite is visible in the scrollRect.

Any tips or suggestions on how to accomplish something like this?

+2  A: 

You could always use

if (Sprite.getBounds().intersects(scrollRect)) {
    //In view
}

as a test. Basic rectangle intersection.

Walt W
Hi, thanks. So I have my scrollRect's y position animated on a mouseover event, confused where I would be doing this check. any hints
Ronn
No problem. To be thorough, whenever you update scrollRect you should check the visibility of each child and update your thumbnails appropriately.
Walt W
ok, so if my mouseover handler looks like this: var rect:Rectangle = mysprite.scrollRect rect.y += 10 mysprite.scrollRect = rectI should be doing the intersect check here? on all the children of mysprite?
Ronn
Yup, right after that, assuming your thumbnails (or their containers, whatever you need to check) are direct children. Note that if you have multiple places where the scrollRect is changed, you might want to move the checks into a separate function like scrollAndCheck(y), which scrolls the scrollRect by y pixels and then does the check.
Walt W
thanks. finally got it working. Although I think there's less of a performance hit by actually just loading all of the images rather then doing all the looping and checking that gets called repeatedly in the mouseover handler. Would not be an issue if it was just a click and one set of checks but the mouseover gets the fan blowin pretty quickly.
Ronn
Yes; unless your list is HUGE, loading all the thumbnails at once is very reasonable. It's not like thumbnails are that large - that's the reason for using thumbnails, right? :) *coughupvote?cough*
Walt W
A: 

Hi there,

I think the easiest way would be to check for overlap between the two rectangles. You can get a bounds rectangle from any DisplayObject with: myObject.getRect():Rectangle, or getBounds():Rectangle. You can then test this against the scroll rectangle for overlap.

There is a native overlap method on Rectangle, (rect1.intersects(rect2)):Boolean. I prefer to use a custom method for performance reasons though:

var overlap:Boolean = (r1.left < r2.right && r1.right > r2.left && r1.top < r2.bottom && r1.bottom > r2.top);

Good luck!

Tyler Egeto