以下代码在桌面上平放的设备上运行时会显示一个红色圆圈('球')和一条线。
当我轻轻地倾斜设备时,圆圈移向线条。当它到达该行时,它会停止,这是预期和期望的行为。
但是,如果我继续倾斜,圆圈会移动通过线。我已经尝试了2天来解决为什么grrr我只是想让圆圈击中线并且不通过它。
有什么想法吗?与该行作为边缘'?
的任何关系干杯, 安迪
import SpriteKit
import CoreMotion
class GameScene: SKScene, SKPhysicsContactDelegate {
var ball : SKShapeNode!
var line : SKShapeNode!
var motionManager = CMMotionManager()
var destX : CGFloat!
var destY : CGFloat!
let ballRadius = CGFloat(20.0)
override func didMoveToView(view: SKView) {
backgroundColor = SKColor.whiteColor()
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
ball = SKShapeNode(circleOfRadius: ballRadius)
ball.fillColor = UIColor.redColor()
ball.position = CGPoint(x: frame.size.width/4, y: frame.size.height / 2)
destX = frame.size.width/4
destY = frame.size.height / 2
ball.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius)
addChild(ball)
line = SKShapeNode()
var lineStart = CGPoint(x: frame.size.width/2, y: 0)
var lineEnd = CGPoint(x: frame.size.width/2, y: frame.size.height)
var linePoints = [lineStart, lineEnd]
var linePos : CGMutablePathRef = CGPathCreateMutable()
CGPathAddLines(linePos, nil, linePoints, 2)
line.path = linePos
line.strokeColor = UIColor.blackColor()
line.physicsBody = SKPhysicsBody(edgeFromPoint: lineStart, toPoint: lineEnd)
addChild(line)
}
override func update(currentTime: NSTimeInterval) {
moveBall()
}
func moveBall() {
motionManager.startAccelerometerUpdatesToQueue(
NSOperationQueue.currentQueue(), withHandler: {
data, error in
var currentX = self.ball.position.x
var currentY = self.ball.position.y
self.destY = currentY - CGFloat(data.acceleration.x * 100)
self.destX = currentX + CGFloat(data.acceleration.y * 100)
}
)
ball.position = CGPoint(x: destX, y: destY)
}
}
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let skView = self.view as! SKView
let scene = GameScene(size: CGSizeMake(
skView.bounds.size.width, skView.bounds.size.height))
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}