Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.85 KB | None | 0 0
  1. //
  2. // ViewController.swift
  3. // MagneticSwitch
  4. //
  5. // Created by MizushimaYusuke on 2017/03/29.
  6. // Copyright © 2017 MizushimaYusuke. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import SpriteKit
  11.  
  12. class ViewController: UIViewController {
  13.  
  14. weak var scene: SKScene?
  15. var fields = [SKFieldNode]()
  16.  
  17. override func viewDidLoad() {
  18. super.viewDidLoad()
  19. setupScene()
  20. createMagnet()
  21. createBall()
  22. }
  23.  
  24. func setupScene() {
  25. let sv = SKView(frame: view.frame)
  26. let s = SKScene(size: view.frame.size)
  27. sv.backgroundColor = UIColor.lightGray
  28. s.physicsWorld.gravity = CGVector(dx: 0, dy: -0.2)
  29. sv.presentScene(s)
  30. view.addSubview(sv)
  31. scene = s
  32.  
  33. sv.showsFields = true
  34. }
  35.  
  36. func createMagnet() {
  37. stride(from: 50, to: view.frame.maxX, by: 100).forEach { x in
  38.  
  39. let magnet = SKSpriteNode(color: .blue, size: CGSize(width: 50, height: 200))
  40. magnet.name = "magnet"
  41. magnet.position = CGPoint(x: x, y: view.center.y + 120)
  42. scene?.addChild(magnet)
  43. magnet.physicsBody = SKPhysicsBody(rectangleOf: magnet.size)
  44. magnet.physicsBody?.isDynamic = false
  45.  
  46. let plus = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 100))
  47. plus.name = "magnet"
  48. plus.position = CGPoint(x: 0, y: -50)
  49. magnet.addChild(plus)
  50.  
  51. let field = SKFieldNode.radialGravityField()
  52. field.isEnabled = true
  53. field.strength = 1
  54. field.position = CGPoint(x: magnet.position.x, y: magnet.position.y - 100)
  55. field.region = SKRegion(radius: 300)
  56. scene?.addChild(field)
  57. fields.append(field)
  58. }
  59. }
  60.  
  61. func createBall() {
  62. let ball = SKShapeNode(circleOfRadius: 30)
  63. ball.position = view.center
  64. ball.fillColor = UIColor.lightGray
  65. scene?.addChild(ball)
  66.  
  67. ball.physicsBody = SKPhysicsBody(circleOfRadius: 30)
  68. ball.physicsBody?.charge = 1
  69. }
  70.  
  71. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  72. if let touch = touches.first {
  73. let p = touch.location(in: scene!)
  74. let node = scene?.nodes(at: p)
  75. .map { n -> SKNode in
  76. if (n.parent?.name == "magnet") { return n.parent! }
  77. return n
  78. }.first
  79. if node?.name == "magnet" {
  80. fields
  81. .filter { abs($0.position.x - node!.position.x) < 5 }
  82. .forEach {
  83. let isEnable = !$0.isEnabled
  84. $0.isEnabled = isEnable
  85. node?.run(SKAction.fadeAlpha(to: isEnable ? 1.0 : 0.5, duration: 0.2))
  86. }
  87. }
  88. }
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement