How do I correctly use allContactedBodies?

删除回忆录丶 提交于 2019-12-02 01:31:19

The allContactedBodies property returns an array of SKPhysicsBody objects. You can access the node to which each physicsBody is attached by using the node property of SKPhysicsBody

NSArray *tempArray = [yourNode.physicsBody allContactedBodies];
for(SKPhysicsBody *body in tempArray)
{
    if([body.node.name isEqualToString:@"theBall"])
        NSLog(@"found the ball");
}

In Swift the same code above can be written like:

val ballNode: SKNode? = yourNode.physicsBody.allContactedBodies().first(where { $0.node.name == "theBall" })?.node

If you read the SKPhysicsBody Class Reference, you should have seen the format for this command.

- (NSArray *)allContactedBodies

The return value is:

An array of SKPhysicsBody objects that this body is in contact with.

Having said that, you would use this code to accomplish what you are asking:

NSArray *tempArray = [yourNode.physicsBody allContactedBodies];
for(SKNode *object in tempArray)
{
    if([object.name isEqualToString:@"theBall"])
        NSLog(@"found the ball");
}

FYI - You will have to run this code in the update: method. This means your app will spend precious processing time every single frame checking for a contact. It would make much more sense to stick with the didBeginContact: instead.

Apparently, when collisions happen very rapidly, contacts with multiple nodes are reported simultaneusly. In this case, only one of the collisions will be detected in didBeginContact, and you may lose the contact you are interested in.

You can detect simultaneous (or almost simultaneous) contacts in didBeginContact as follow, and use it to apply whatever logic you need.

NSArray *tempArray = [mySprite.physicsBody allContactedBodies];
BOOL contactWithNodeOfInterest = NO;
int i = 0;
for(SKPhysicsBody *body in tempArray)
   {
    if([body.node.name isEqualToString:@"nodeOfInterest"]) { contactWithNodeOfInterest = YES; }
    NSLog(@"Contacts: %i %@",i,body.node.name);
    i = i + 1;
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!