SpriteKitを使ってるときに、四角形とか丸とかを作りたいときに使う。
//長方形 let rect = SKShapeNode(rectOfSize: CGSize(width: 50, height: 50)) rect.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5) rect.lineWidth = 5.0 rect.strokeColor = SKColor.blueColor() rect.fillColor = SKColor.blueColor() self.addChild(rect) //円 let circle = SKShapeNode(circleOfRadius: 10) circle.lineWidth = 0.0 circle.fillColor = SKColor.greenColor() circle.position = CGPoint(x: self.size.width * 0.5, y:self.size.height - 20) self.addChild(circle)
重力加えてみる
下記のようにphysicsWorld.gravityにCGVectorを設定する。
class GameScene : SKScene{ override func didMoveToView(view: SKView) { //重力 self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -2.0) //長方形 let rect = SKShapeNode(rectOfSize: CGSize(width: 50, height: 50)) rect.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5) rect.lineWidth = 5.0 rect.strokeColor = SKColor.blueColor() rect.fillColor = SKColor.blueColor() let physicsBody = SKPhysicsBody(rectangleOfSize: rect.frame.size) physicsBody.dynamic = false //重力無効にする rect.physicsBody = physicsBody self.addChild(rect) //円 let radius:CGFloat = 10 let circle = SKShapeNode(circleOfRadius: radius) circle.lineWidth = 0.0 circle.fillColor = SKColor.greenColor() circle.position = CGPoint(x: self.size.width * 0.5, y:self.size.height - 20) circle.physicsBody = SKPhysicsBody(circleOfRadius: radius) //重力有効にする self.addChild(circle) } }
画像も追加してみる
画像はSKSpriteNodeというのを使ってつくれる。
class GameScene : SKScene{ override func didMoveToView(view: SKView) { //重力 self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -2.0) //長方形 let rect = SKShapeNode(rectOfSize: CGSize(width: 50, height: 50)) rect.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5) rect.lineWidth = 4.0 rect.strokeColor = SKColor.blueColor() rect.fillColor = SKColor.blueColor() let physicsBody = SKPhysicsBody(rectangleOfSize: rect.frame.size) physicsBody.dynamic = false //重力無効にする rect.physicsBody = physicsBody self.addChild(rect) //円 let radius:CGFloat = 10 let circle = SKShapeNode(circleOfRadius: radius) circle.lineWidth = 0.0 circle.fillColor = SKColor.greenColor() circle.position = CGPoint(x: self.size.width * 0.5 - 28, y:self.size.height - 20) circle.physicsBody = SKPhysicsBody(circleOfRadius: radius) //重力有効にする self.addChild(circle) //画像 let texture = SKTexture(imageNamed: "rocket") let img = SKSpriteNode(texture: texture) img.position = CGPoint(x: self.size.width * 0.5, y:self.size.height - 100) img.physicsBody = SKPhysicsBody(texture: texture, size: img.size) self.addChild(img) } }