您无需编写太多代码即可使球从屏幕边缘弹起。物理环境可以处理以上所有内容,您只需要以正确的方式实例化精灵即可。
首先,您必须将场景的物理主体设置如下:
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
在场景的 .h 文件中创建两个位掩码类别:
static const uint8_t ballCategory = 1;
static const uint8_t wallCategory = 2;
并给场景的物理体一个类别:
self.physicsBody.categoryBitMask = wallCategory;
然后创建你的精灵:
SKSpriteNode *spriteNode = [SKSpriteNode spriteNodeWithImageNamed:@"ball.png"];
spriteNode.name = @"ball";
spriteNode.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:25];
spriteNode.position = CGPointMake(10.0,10.0); //or anything you want
spriteNode.physicsBody.dynamic = YES;
spriteNode.physicsBody.affectedByGravity = NO;
spriteNode.physicsBody.categoryBitMask = ballCategory;
spriteNode.physicsBody.collisionBitMask = wallCategory;
spriteNode.physicsBody.restitution = 1.0;
spriteNode.physicsBody.friction = 0.0;
spriteNode.physicsBody.linearDamping = 0.0;
spriteNode.physicsBody.angularDamping = 0.0;
[self addChild:spriteNode];
而不是给 spriteNode[SKAction moveTo: duration:]
,对其物理体施加脉冲。
CGVector impulse = CGVectorMake(1.0,1.0);
[spriteNode.physicsBody applyImpulse:impulse];
瞧!球将从墙上弹起,没有任何东西可以阻止它。
.h 文件应如下所示:
#import <SpriteKit/SpriteKit.h>
static const uint8_t ballCategory = 1;
static const uint8_t wallCategory = 2;
@interface BallBounce : SKScene
@end
.m 文件应如下所示:
#import "BallBounce.h"
@implementation BallBounce
-(instancetype)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody.categoryBitMask = wallCategory;
SKSpriteNode *spriteNode = [SKSpriteNode spriteNodeWithColor:[UIColor greenColor] size:CGSizeMake(50, 50)];
spriteNode.name = @"ball";
spriteNode.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:25];
spriteNode.position = CGPointMake(10.0,10.0); //or anything you want
spriteNode.physicsBody.dynamic = YES;
spriteNode.physicsBody.affectedByGravity = NO;
spriteNode.physicsBody.categoryBitMask = ballCategory;
spriteNode.physicsBody.collisionBitMask = wallCategory;
spriteNode.physicsBody.restitution = 1.0;
spriteNode.physicsBody.friction = 0.0;
spriteNode.physicsBody.linearDamping = 0.0;
spriteNode.physicsBody.angularDamping = 0.0;
[self addChild:spriteNode];
CGVector impulse = CGVectorMake(100.0,100.0);
[spriteNode.physicsBody applyImpulse:impulse];
}
return self;
}
@end