使用 CALayers 捕捉
我正在使用 -mouseDragged
方法移动一些 CALayers,现在我想在它们足够接近时(或者当它们稍微重叠时)“捕捉”它们。 每层都不是“正方形”:我正在绘制不同的多边形。
我认为做到这一点的方法是:
- 获取正在移动的图层的位置;
- 获取重叠图层或靠近被移动图层的图层;
- 在(2)为真的多边形的每一侧,我需要检查移动层的一侧与“附近”的层的一侧之间的最大距离(与层的一侧成直角) (当层重叠时,这是一个负值)。
- 相应地移动图层。
我不知道这是否是正确的方法。我想到的第一件事是:
- 如果我可以“卡入”多个侧面会发生什么?
而且,即使我尝试这种方式,我也不知道如何处理(2)和(3)。
有更好的方法吗?
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:
- get the position of the layer being moved;
- get the overlapping layers or the layers that are near the layer being moved;
- 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).
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这并不容易。因为 CALayers 不是矢量图形,所以您必须处理任何可能的形状(例如龙的图片)。
正确的碰撞很困难。相反,尝试用您想要捕捉到的形状来测试鼠标/触摸的位置。
您可以通过检查鼠标位置处每个可能的捕捉层的透明度来完成此操作。请参阅此问题了解有关如何执行此操作的信息。
更困难但效果更好:
使用 2D 物理引擎,例如 Chipmunk< /a> 或 Box2D 进行碰撞检测。
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.