1

下面的代码在平放在桌面上的设备上运行时会显示一个红色圆圈(“球”)和一条线。

当我轻轻地倾斜设备时,圆圈会朝这条线移动。当它到达线路时,它会停止,这是预期和期望的行为。

但如果我继续小费,圆圈就会穿过这条线。我已经尝试了 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
}
}
4

0 回答 0