限制触摸移动的物体与墙壁碰撞?

发布于 2024-09-02 23:06:06 字数 769 浏览 6 评论 0原文

我正在尝试创建一个非常简单的游戏,您可以在其中拖动简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

毁梦 2024-09-09 23:06:06

好吧,发现我的错误..

我必须这样做:

if (CGRectContainsPoint (CGRectMake(0, 0, 800, 768), [touch locationInView:self.view]))

而不是这样:

if (CGRectContainsRect (CGRectMake(0, 0, 800, 768), [myImage frame]))

是的,很傻..

ok found my mistake..

I had to do this:

if (CGRectContainsPoint (CGRectMake(0, 0, 800, 768), [touch locationInView:self.view]))

instead of this:

if (CGRectContainsRect (CGRectMake(0, 0, 800, 768), [myImage frame]))

ye, quite silly..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文