Let us know if you want to be confined to any other shape.
A rotated rectangle can be done by first rotating position offset by the -angle, then clamping by the size, and rotating the angle back again.
A circle shape can be done by measuring the angle and distance, clamping the distance, the calculating a new position from that.
If you want to limit it to an object’s collision polygon, and the polygon is a convex polygon, you can take the position offset and clip it by each edge with a bit of math. Namely with (x-x0)*cos(a)+(y-y0)*sin(a) you can measure a distance along a certain direction. If you use that with an angle 90 degrees from an edge you can find if a point is on either side of an edge and clip it if on one side.
Finally if you want to limit the motion to a concave shape you probably could do that by storing the players previous position and calculating the line intersections between the edges and the segment connecting the new and old position, and finally just stop at the first intersection. I don’t think that would provide any wall sliding but one idea for that involves decomposing the concave shape into convex ones, but it may be a bit more involved. Basically you’d check for overlaps with edges, the limit to the convex sub polygon that edge is part of.
Also depending on the shape you could possibly utilize sdfs to implement the limit. That would let you have shapes with rounded corners.
Taking the sdf idea further, you could make an approximate sdf on a 2d grid of any shape and raymarch through that. The main complexity there would be generating it.
There are some low tech approaches too. You could store the old and new positions and use a loop with an overlap test to move but stop short of leaving the other object.
Dop’s suggestion to place invisible solid objects around the shape is probably the easiest no code option. Another is to make the collision polygon a crescent shape that you wrap around the object image so there’s a thick wall around it.
With collision based approaches beware of tunneling. Aka with high speeds and thin walls the collisions can be missed and objects will move right through.
There are probably other approaches with varying pros and cons.