如何指定UIImage initWithImage的位置以检测图像的冲突

时间:2014-01-14 00:50:41

标签: ios objective-c uiimage

我已经查询了这个问题的所有相关问题,但没有任何成功。 问题可能很简单:

我想检测两个几何对象之间的碰撞,这些几何对象在给定时间以彼此碰撞的方式进行动画处理。

为了使用方法CGRectIntersectsRect,我必须使用几何对象的实际图像的大小完全初始化UIImage,这样如果图像/帧真正碰撞,它只返回一个碰撞。

那么我如何指定postion来放置我的图像我有intiliazid和initWithImage。

我无法使用方法initWithFrame:CGRectMake,因为我不希望UIImageview形状为矩形。

不起作用的示例:

circleYellow = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, 50, 50)];
circleYellow.image = [UIImage imageNamed:images[arc4random() % 5]];


circleYellow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:images[arc4random() % 5]]];

4 个答案:

答案 0 :(得分:0)

UIImageView和它的超类UIView总是创建矩形。来自UIView class reference

  

UIView类在屏幕上定义了一个矩形区域......

听起来SpriteKit可能就是您所需要的 - 请查看sprite kit programming guide

答案 1 :(得分:0)

我建议使用SpriteKit:

//Create a SpriteNode loading your image
SKSpriteNode *cicleYellow = [SKSpriteNode spriteNodeWithImageNamed:images[arc4random() % 5]];

//Set the size and the position of the Sprite
circleYellow.size = CGSizeMake(50,50);
circleYellow.position = CGPointMake(0, self.view.frame.size.height);

//Create a circlePhisicsBody and add it to the Sprite
SKPhysicsBody *circlePhisicsBody = [SKPhysicsBody bodyWithCircleOfRadius:cicleYellow.size.width/2.0f];
cicleYellow.physicsBody = circlePhisicsBody;

查看Apple documentation如何使用Sprite Kit。

答案 2 :(得分:0)

我建议你查看cocos2d。它具有处理精灵的工具,通过屏幕上的动作(动画)更新其位置等等。

检测两个精灵的碰撞就像是:

-(void)update(float dt)
{
  CGRect rect1 = [sprite1 boundingBox];
  CGRect rect2 = [sprite2 boundingBox];

  if (CGRectIntersectsRect(rect1, rect2))
  {
      // Do something about the collision...
  }
}

如果您需要更复杂的运动建模,或者您希望能够碰撞任意形状而不仅仅是边界框,Box2D内置。还有很多可用的示例。

这有用吗?

答案 3 :(得分:0)

你需要一些计时器功能来检查它,但是用于检测矩形之间碰撞的算法是非常直接的(方形A和方形B):

//If any of the sides from A are outside of B 
if( bottomA <= topB ) { return false; } 
if( topA >= bottomB ) { return false; } 
if( rightA <= leftB ) { return false; } 
if( leftA >= rightB ) { return false; } 
//If none of the sides from A are outside B return true;

如果你需要为圈子做这件事只是一个很好的教程:http://gamedevelopment.tutsplus.com/tutorials/when-worlds-collide-simulating-circle-circle-collisions--gamedev-769