Hit detection of mouse in rotated rectangle

I just hit a wall while patching - how in the four v’s can I make a hit detection with the mouse inside a rotated rectangle?

Found a way using VL.PolyTools by @tobyk

RotatedRectContainsPointPolyTools.vl (13.3 KB)

i guess, you need to rotate the mouse coordinate accordingly…

In the chat @bjoern and @elektromeier pointed me to this solution:

inverse transform the mouse coordinate with the transformation of the rect
then you can check the range i think its -0.5 to 0.5

The patch from the screenshot is in VL.Addons

You mean like so? I guess @blacktronics also suggested something similar in the chat.

RotatedRectContainsPointPolar.vl (13.5 KB)

yeah
quite some solutions already )

I would say there are three approaches, the first two will support hittest of almost any shape. The third is strictly for rotated rectangles.


Slowest but most flexible

So you don’t even need VL.Polytools for this, the Skia Path nodes which you are using to create a PolyPath already have a Contains function. (Look in the node browser with advanced aspect > Paths > Contains). Of Course PolyTools is a nicer way to handle these paths.

The Paths.Contains function is much slower than just detecting a non-rotated rectangle hit so if you need to optimise to do a lot of these then could be worth doing a first hit test on the non-rotated rectangle before checking the SKpath. You can get that non-rotated bounding box of an SKPath with Paths.GetTightBounds.

Nice thing about the SKPaths approach is it should work on basically any skia shape (as long as it’s not self-intersecting or something weird).


Middle approach

This one does need VL.PolyTools.
If you use the Polygon datatype included it also has a Contains function.
This limits you to using Polygons made of straight lines but it should be faster than the SKPath contains because the straight line polygons are less complex than shapes with curves. (Although if you only had simple shapes in the SKPath I wonder if the SKPath.Contains optimises for that… not sure)

Again might freak out on weird polygons with complex self-intersections.


Fastest approach

This would be following the transform solutions from @bjoern and @elektromeier or the polar one from @Blacktronics that you @Chk also posted above. Strictly for rotated rectangles only.

If you want a deeper understanding of the maths here then check out the helppatch in VL.ExtendedTutorials Maths tutorials #06 2D space remapping.
That helppatch attempts to do a vvvv version of what Freya Holmér explains in this videos

3 Likes