Skip to content

Instantly share code, notes, and snippets.

@dreammonkey
Forked from PrimaryFeather/ClippedSprite.as
Created June 11, 2012 14:02
Show Gist options
  • Save dreammonkey/2910231 to your computer and use it in GitHub Desktop.
Save dreammonkey/2910231 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.Rectangle;
import starling.core.RenderSupport;
import starling.core.Starling;
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
{
// without a clip rect, the sprite should behave just like before
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 globalPoint:Point = localToGlobal(localPoint);
if (mClipRect.contains(globalPoint.x * scale, globalPoint.y * scale))
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