# Web Dev Needs Game Dev help! 2D Clamp/Hit detection?

## Recommended Posts

Hey all my first post here and i need some help, i have googled the crap out of this question and no luck, but alas it seems to me this must be a common problem in the game dev world. Ill skip the back story and get down to it.

Scenario:

OUTER BOUNDARY: (rectangle)

A MOVEABLE POINT: (smaller rectangle)

What i need to do is clamp the POINT so it cannot be dragged outside of the BOUNDARY even when rotated. If the boundary isnt rotated it' s super easy, did it within 5 minutes, just compare max/min X & Y. However, both the BOUNDARY and POINT can be rotated to any angle, and furthermore size will not be constant depending on device.

Now, i have learned about some basic hit detection AABB, parallel axis theorem etc and have successfully implemented several algorithms to detect whether there is a collision between the edges, but knowing when the point has encountered an edge is only half the problem... i need to know which way to translate after the edge is touching in order to successfully clamp it within the rotated boundary.

Im close but no cigar:

• I detect the 4 corners of each rectangle
• Then compare each segment of both rectanges to check for an intersection
• If a hit occurs, I clamp the inner rectangle to the Max/Min of the intersection point

This seems to somewhat work, however I am getting corner overlap depending on the toation/side I am touching.

Is there a more standard way to solve the probem?

Is comparing the line segments the way to do it?

##### Share on other sites

So still chugging along here, have tried a different approach:

Becuase it easy to calculate the boundary/offset on an aligend bounding box what i did was build a rotation matrix to transform and undo the rotation offset (-deg whatever it is rotated) then determine the min/max offset and clamp it, then rotate the POINT and BOUNDARY back to original position.

Again, so close but it seems to be just off by a small constant value, left/right side are perfect but up/down slightly offset but correct  angel (clamping just outside/inside edge of the BOUNDARY)

This is maddening im missing something in the formula i think..

Anyone?

##### Share on other sites

Well 3 days later i finally got it all on my own, and holy crap it was hard, the solution was quite elegant all said and done....

thanks for all the help guys!

,,!,,

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.