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



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

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

为了使用CGRectIntersectsRect方法,我必须使用几何对象的实际图像的大小精确地初始化UIImage,以便在图像/帧真正碰撞时仅返回碰撞。

那么我如何指定放置我与 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]]];

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

检测两个精灵的碰撞变成这样:

-(void)update(float dt)
{
  CGRect rect1 = [sprite1 boundingBox];
  CGRect rect2 = [sprite2 boundingBox];
  if (CGRectIntersectsRect(rect1, rect2))
  {
      // Do something about the collision...
  }
}

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

这有帮助吗?

UIImageView 及其超类 UIView 总是创建矩形。从 UIView 类参考:

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

听起来SpriteKit可能是你需要的 - 查看精灵套件编程指南。

我建议使用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 文档。

你需要一些计时器函数来时不时地检查这一点,但用于检测矩形之间碰撞的算法非常简单(正方形 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

最新更新