Skip to content

Instantly share code, notes, and snippets.

@ekeeper
Forked from PrimaryFeather/ClippedSprite.as
Created June 5, 2012 17:02
Show Gist options
  • Save ekeeper/2876250 to your computer and use it in GitHub Desktop.
Save ekeeper/2876250 to your computer and use it in GitHub Desktop.
Simple Sprite subclass with a rectangular mask in stage coordinates
package starling.extensions
{
import flash.display3D.Context3D;
import flash.geom.Point;
import flash.geom.Rectangle;
import starling.core.RenderSupport;
import starling.core.Starling;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.errors.MissingContextError;
public class ClippedSprite extends Sprite
{
private var mClipRect:Rectangle;
public override function render(support:RenderSupport, alpha:Number):void
{
if (mClipRect == null) super.render(support, alpha);
else
{
var context:Context3D = Starling.context;
if (context == null) throw new MissingContextError();
support.finishQuadBatch();
context.setScissorRectangle(mClipRect);
super.render(support, alpha);
support.finishQuadBatch();
context.setScissorRectangle(null);
}
}
public override function hitTest(localPoint:Point, forTouch:Boolean=false):DisplayObject
{
if (mClipRect == null) return super.hitTest(localPoint, forTouch);
// on a touch test, invisible or untouchable objects cause the test to fail
if (forTouch && (!visible || !touchable)) return null;
var scale:Number = Starling.current.contentScaleFactor;
var pointX:Number = ((parent ? parent.x : 0) + localPoint.x) * scale;
var pointY:Number = ((parent ? parent.y : 0) + localPoint.y) * scale;
if (mClipRect.contains(pointX, pointY))
return super.hitTest(localPoint, forTouch);
else
return null;
}
public function get clipRect():Rectangle
{
var scale:Number = Starling.current.contentScaleFactor;
return new Rectangle(mClipRect.x / scale, mClipRect.y / scale,
mClipRect.width / scale, mClipRect.height / scale);
}
public function set clipRect(value:Rectangle):void
{
var scale:Number = Starling.current.contentScaleFactor;
if (mClipRect == null) mClipRect = new Rectangle();
mClipRect.x = scale * value.x;
mClipRect.y = scale * value.y;
mClipRect.width = scale * value.width;
mClipRect.height = scale * value.height;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment