Starling_Padding_HitTest

When developing with Starling, have you ever wished you could increase your girth? Wait… no NOT that kind of increase!
(Ahem Ahem)  I mean… the size of the hitTest() area of your objects.

When developing games for Mobile devices, you have to be aware that most people simply don’t have stylus-sized fingertips. Let’s face it… most of us have FAT fingers! Or at least that’s what it seems our touch devices  are telling us.

Alright so how do you fatten-up the touch area of your Sprite objects? Here’s how!

Using a Padding Property to Inflate the Bounds Rectangle

Assuming that you’re already subclassing starling.display.Sprite to create most of your game entities in your game, you can add the following get/set accessor for a padding property, and override the hitTest method so that it simply “inflates ” whatever results it would normally spit back out.

// ... Somewhere in your custom subclass of starling.display.Sprite ...

		public function get padding():Number { return _padding; }
		public function set padding(value:Number):void {
			_padding = value;
		}
		
		public override function hitTest(localPoint:Point, forTouch:Boolean = false):DisplayObject {
			// on a touch test, invisible or untouchable objects cause the test to fail
            if (forTouch && (!visible || !touchable)) return null;
			
			var theBounds:Rectangle = getBounds(this);
			theBounds.inflate(_padding, _padding);
			
			if (theBounds.containsPoint(localPoint)) return this;
			return null;
		}

// ...

Notice that this also supports negative inflation (shrinkage… that’s right!), so you can actually make some Sprites harder to touch than normal.

Hope this Starling Quick Tip can help you make your Sprites easier to touch!

Thanks for reading!