限制触摸移动的物体与墙壁碰撞?
我正在尝试创建一个非常简单的游戏,您可以在其中拖动简单的 imageView。问题是框架中有一堵墙(只是一个矩形),图像不应该放在上面。所以我做了这样的事情:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
if ([touch view] == myImage) {
if (CGRectContainsRect (CGRectMake(0, 0, 800, 768), [myImage frame]))
{
myImage.center = [touch locationInView:self.view];
}
}
}
但问题是图像确实超出了它的范围,然后卡在那里,触摸移动结束了。
所以我添加了这个:
else if (CGRectIntersectsRect (CGRectMake(801, 0, 223, 768), [myImage frame])) {
CGPoint touchedPoint = [touch locationInView:self.view];
myImage.center = CGPointMake(730, touchedPoint.y);
}
但这使得图像在与“墙”相交时开始闪烁,并最终卡在那里。
我觉得必须有一个简单的方法来做到这一点。有人可以启发我吗?
I'm trying to create a very simple game where you can drag a simple imageView. The thing is there is a wall in the frame (just a rectangle) on which the image should not go. so I did something like this:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
if ([touch view] == myImage) {
if (CGRectContainsRect (CGRectMake(0, 0, 800, 768), [myImage frame]))
{
myImage.center = [touch locationInView:self.view];
}
}
}
But the problem was that the image did went out of it's bounds and then got stuck there and the touchesmoved ended.
so I've added this:
else if (CGRectIntersectsRect (CGRectMake(801, 0, 223, 768), [myImage frame])) {
CGPoint touchedPoint = [touch locationInView:self.view];
myImage.center = CGPointMake(730, touchedPoint.y);
}
But this made the image to start flickering when intersecting with the "wall" and eventually got stuck there either.
I feel there must be a simple way to do that. could anyone enlighten me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,发现我的错误..
我必须这样做:
而不是这样:
是的,很傻..
ok found my mistake..
I had to do this:
instead of this:
ye, quite silly..