Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // MagneticSwitch
- //
- // Created by MizushimaYusuke on 2017/03/29.
- // Copyright © 2017 MizushimaYusuke. All rights reserved.
- //
- import UIKit
- import SpriteKit
- class ViewController: UIViewController {
- weak var scene: SKScene?
- var fields = [SKFieldNode]()
- override func viewDidLoad() {
- super.viewDidLoad()
- setupScene()
- createMagnet()
- createBall()
- }
- func setupScene() {
- let sv = SKView(frame: view.frame)
- let s = SKScene(size: view.frame.size)
- sv.backgroundColor = UIColor.lightGray
- s.physicsWorld.gravity = CGVector(dx: 0, dy: -0.2)
- sv.presentScene(s)
- view.addSubview(sv)
- scene = s
- sv.showsFields = true
- }
- func createMagnet() {
- stride(from: 50, to: view.frame.maxX, by: 100).forEach { x in
- let magnet = SKSpriteNode(color: .blue, size: CGSize(width: 50, height: 200))
- magnet.name = "magnet"
- magnet.position = CGPoint(x: x, y: view.center.y + 120)
- scene?.addChild(magnet)
- magnet.physicsBody = SKPhysicsBody(rectangleOf: magnet.size)
- magnet.physicsBody?.isDynamic = false
- let plus = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 100))
- plus.name = "magnet"
- plus.position = CGPoint(x: 0, y: -50)
- magnet.addChild(plus)
- let field = SKFieldNode.radialGravityField()
- field.isEnabled = true
- field.strength = 1
- field.position = CGPoint(x: magnet.position.x, y: magnet.position.y - 100)
- field.region = SKRegion(radius: 300)
- scene?.addChild(field)
- fields.append(field)
- }
- }
- func createBall() {
- let ball = SKShapeNode(circleOfRadius: 30)
- ball.position = view.center
- ball.fillColor = UIColor.lightGray
- scene?.addChild(ball)
- ball.physicsBody = SKPhysicsBody(circleOfRadius: 30)
- ball.physicsBody?.charge = 1
- }
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- if let touch = touches.first {
- let p = touch.location(in: scene!)
- let node = scene?.nodes(at: p)
- .map { n -> SKNode in
- if (n.parent?.name == "magnet") { return n.parent! }
- return n
- }.first
- if node?.name == "magnet" {
- fields
- .filter { abs($0.position.x - node!.position.x) < 5 }
- .forEach {
- let isEnable = !$0.isEnabled
- $0.isEnabled = isEnable
- node?.run(SKAction.fadeAlpha(to: isEnable ? 1.0 : 0.5, duration: 0.2))
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement