Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created September 18, 2013 07:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/6605801 to your computer and use it in GitHub Desktop.
Save jmcd/6605801 to your computer and use it in GitHub Desktop.
Small SpriteKit demo
#import "MyScene.h"
@interface MyScene () <SKPhysicsContactDelegate>
@end
@implementation MyScene {
NSMutableSet *_notCrashedPhysicsBodies;
}
static const uint32_t carCategory = 0x1 << 0;
const float worldScale = 10; // 1m == 10pt
const float carLength = 4;
const float carWidth = 2;
const float carMass = 1000;
const float speedLimit = 30 * 1.609 * 1000 / 3600; // 30 mph, in ms^-1
const float accelerationForce = 10000; // 10 kN
- (id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
_notCrashedPhysicsBodies = [NSMutableSet set];
self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGPointZero;
CGPoint location = CGPointMake(size.width / 2, size.height / 2);
SKNode *parkedCar = [self addCarAtLocation:location];
parkedCar.physicsBody.linearDamping = 1;
}
return self;
}
- (SKSpriteNode *)addCarAtLocation:(CGPoint)location {
CGSize size = CGSizeMake(carLength * worldScale, carWidth * worldScale);
SKPhysicsBody *physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:size];
physicsBody.mass = carMass;
physicsBody.categoryBitMask = carCategory;
physicsBody.collisionBitMask = carCategory;
physicsBody.contactTestBitMask = carCategory;
physicsBody.angularDamping = 10;
SKSpriteNode *carSprite = [SKSpriteNode spriteNodeWithImageNamed:@"car.png"];
carSprite.color = [UIColor colorWithRed:(float) rand() / RAND_MAX green:(float) rand() / RAND_MAX blue:(float) rand() / RAND_MAX alpha:1];
carSprite.colorBlendFactor = 0.8;
carSprite.position = location;
carSprite.physicsBody = physicsBody;
[self addChild:carSprite];
return carSprite;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKSpriteNode *sprite = [self addCarAtLocation:location];
[_notCrashedPhysicsBodies addObject:sprite.physicsBody];
}
}
- (void)update:(CFTimeInterval)currentTime {
for (SKPhysicsBody *carPhysicsBody in _notCrashedPhysicsBodies) {
CGFloat velocity = carPhysicsBody.velocity.dx;
NSLog(@"%f mph", velocity * 3600 / (1000 * 1.609 * worldScale));
if (velocity < speedLimit * worldScale) {
[carPhysicsBody applyForce:CGVectorMake(accelerationForce * worldScale, 0)];
}
}
}
- (void)didBeginContact:(SKPhysicsContact *)contact {
for (SKPhysicsBody *body in @[contact.bodyA, contact.bodyB]) {
body.linearDamping = 1;
[_notCrashedPhysicsBodies removeObject:body];
}
}
@end
@jmcd
Copy link
Author

jmcd commented Sep 18, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment