Question

I am moving a few CALayers using the -mouseDragged method, and now I would like to "snap" them when they are sufficiently near (or when they are overlapping just a little bit). Each layer is not a "square": I am drawing different polygons.

I thought that a way to do this is to:

  1. get the position of the layer being moved;
  2. get the overlapping layers or the layers that are near the layer being moved;
  3. On each side of the polygon in which (2) is true, I need to check the maximum distance (at right angles to the side of the layer) between the side of the moving layer and the side of the layer that is "near" (this is a negative value when the layers overlap).
  4. move the layer accordingly.

I don't know if this is a correct approach. The first thing that comes in my mind is:

  • What happens if I can "snap" in more than one side?

And, even if I try this way, I have no idea what to do regarding (2) and (3).

Is there a better way to do that?

Was it helpful?

Solution

This is not easy. Because CALayers are not vector graphics you have to deal with any possible shape (eg. picture of a dragon.)

Proper collisions are difficult. Instead try hit testing the mouse/touch's position with the shape you want to snap to.

You can do this by checking the transparency of each of the possible snapping layers at the mouse location. See this question for information of how to do this.

More Difficult but Better Results:

Use a 2D physics engine like Chipmunk or Box2D to do your collision detection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top