Sprite Kit与子Sprite的碰撞检测 [英] sprite kit collision detection with child sprite

查看:75
本文介绍了Sprite Kit与子Sprite的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测两个精灵之间的碰撞,但是我无法使用子精灵来做到这一点.

I'm trying to detect collisions between two sprites but I'm unable to do this with a child sprite.

self.player = [[Player alloc] initWithImageNamed:@"player"];
self.player.position = CGPointMake(150, 75);
[self addChild:self.player];

      _object = [SKSpriteNode spriteNodeWithImageNamed:@"object"];
      _object.position = CGPointMake(-40, 27);
       [self.player addChild:_object];

那我有这样的碰撞检测

- (void)checkCollisions {
[self.map enumerateChildNodesWithName:@"enemy"
usingBlock:^(SKNode *node, BOOL *stop){SKSpriteNode *enemy = (SKSpriteNode *)node;
if (CGRectIntersectsRect(enemy.frame, _object.frame)) {
[enemy removeFromParent];
}
}]; }

*这不起作用!!!但是如果我使用:

*This does not work!!! but if I use :

CGRectIntersectsRect(enemy.frame, self.player.frame)  

我可以检测到与主体的碰撞.如何为另一个精灵的孩子进行碰撞检测?

I can detect a collision with the main body. how do I do collision detection for a child of another sprite?

推荐答案

子节点的positionframe属性是相对于其parent的,您需要在代码中加以说明.

The child node's position and frame property are relative to it's parent, which you need to account for in your code.

SKNode有两种方法可以帮助您将给定SKNodeposition转换为另一个节点的坐标空间或从另一个节点的坐标空间转换为

SKNode has two methods that can help you with converting the position of a given SKNode to/from the coordinate spaces of another node:

convertPoint:fromNode:
convertPoint:toNode:

您可以使用它们将SKNodeposition属性转换为另一个坐标空间.您要做的是将_object的位置转换为敌人的坐标空间,反之亦然,然后将具有新位置的临时CGRect用于您的CGRectIntersectsRect支票.

You can use those to convert a SKNode's position property to another coordinate space. What you want to do is convert the _object's position to the coordinate space of the enemy or visa versa and then use a temporary CGRect with that new position for your CGRectIntersectsRect check.

这是一个例子:

CGPoint globalPosition = [self.player convertPoint:_object.position toNode:self.player.parent];
CGRect tempRect = CGRectMake(globalPosition.x, globalPosition.y, _object.frame.size.width, _object.frame.size.height);

if (CGRectIntersectsRect(enemy.frame, _object.frame))
{
   // collision occurred
}

此代码假设您的敌人和玩家在同一坐标空间中. (具有相同的父母)

This code is assuming that your enemy and your player are in the same coordinate space. (have the same parent)

这篇关于Sprite Kit与子Sprite的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆