我想要的模式是汽车中的变速杆。它由大约 9 条 90 度角的直线组成,我需要用户沿着这些直线拖动 UIView。
我的第一种方法是检查视图中心的坐标,如果满足某些条件,则适当地启用/禁用 x/y。这导致了一个冗长复杂的 if 语句,维护起来会很麻烦。它在大多数情况下都有效 - 偶尔会卡住,但我知道我需要做些什么来修复它。
我的第二个想法是在我的路径周围构建一个非常简单的矩形集合,中间有一个足够宽的空间,以允许一个正方形,我将锚定到我想要移动的视图上。然后我就可以使用碰撞检测来保持沿路径的视图。这似乎适用于非常基本的块状路径,但不适用于更复杂的路径。
还有其他方法可以达到我想要的效果吗?
顺便说一句,这是我对第一个场景的超级粗略和低效的测试:
// The reason we aren't using if else is because we want to allow both x and y movement if they are on a corner.
if(knob.center.x >= 218 && knob.center.x <= 240 && knob.center.y == 140) {
// First line
canMoveX = TRUE;
if(translation.x + knob.center.x < 218) {
translation.x = knob.center.x - 218;
}
else if(translation.x + knob.center.x > 240) {
translation.x = 240 - knob.center.x;
}
}
if(knob.center.x == 240 && knob.center.y >= 140 && knob.center.y <= 230) {
// Second Line
canMoveY = TRUE;
if(translation.y + knob.center.y < 140) { translation.y = knob.center.y - 140; }
else if(translation.y + knob.center.y > 230) { translation.y = 230 - knob.center.y; }
}
if(knob.center.x >= 224 && knob.center.x <= 240 && knob.center.y == 230) {
// Third Line
canMoveX = TRUE;
if(translation.x + knob.center.x < 224) { translation.x = knob.center.x - 224; }
else if(translation.x + knob.center.x > 240) { translation.x = 240 - knob.center.x; }
}
if(knob.center.x == 224 && knob.center.y >= 230 && knob.center.y <= 285) {
// Fourth Line
canMoveY = TRUE;
if(translation.y + knob.center.y < 230) { translation.y = knob.center.y - 230; }
else if(translation.y + knob.center.y > 285) { translation.y = 285 - knob.center.y; }
}
if(knob.center.x >= 205 && knob.center.x <= 224 && knob.center.y == 285) {
// Fifth Line
canMoveX = TRUE;
if(translation.x + knob.center.x < 205) { translation.x = knob.center.x - 205; }
else if(translation.x + knob.center.x > 224) { translation.x = 224 - knob.center.x; }
}
if(knob.center.x == 205 && knob.center.y >= 285 && knob.center.y <= 337) {
// Sixth Line
canMoveY = TRUE;
if(translation.y + knob.center.y < 285) { translation.y = knob.center.y - 285; }
else if(translation.y + knob.center.y > 337) { translation.y = 337 - knob.center.y; }
}
if(knob.center.x >= 133 && knob.center.x <= 205 && knob.center.y == 337) {
// Seventh Line
canMoveX = TRUE;
if(translation.x + knob.center.x < 133) { translation.x = knob.center.x - 133; }
else if(translation.x + knob.center.x > 205) { translation.x = 205 - knob.center.x; }
}
if(canMoveX) {
[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y)];
[gesture setTranslation:CGPointZero inView:[piece superview]];
}
if(canMoveY) {
[piece setCenter:CGPointMake([piece center].x, [piece center].y + translation.y)];
[gesture setTranslation:CGPointZero inView:[piece superview]];
}