移动SKSpriteNode直到触摸结束

时间:2015-05-04 23:20:02

标签: xcode swift

我在Swift的Spite Kit中创建了这个游戏。我创造了一艘船,我可以确定它的位置是在船的位置上方或下方。船将移向我放置手指的Y轴。但是此时船只只会移动一定的数量,在这种情况下为30或-30。我怎样才能重写这段代码,以便船只继续移动直到我释放手指?

谢谢!

func addShip() {
    // Initializing spaceship node
    ship = SKSpriteNode(imageNamed: "spaceship")
    ship.setScale(0.45)
    ship.zRotation = CGFloat(-M_PI/2)

    // Adding SpriteKit physics body for collision detection
    ship.physicsBody = SKPhysicsBody(rectangleOfSize: ship.size)
    ship.physicsBody?.categoryBitMask = UInt32(shipCategory)
    ship.physicsBody?.affectedByGravity = false
    ship.physicsBody?.dynamic = true
    ship.physicsBody?.contactTestBitMask = UInt32(obstacleCategory)
    //NEWLY ADDED
    ship.physicsBody?.contactTestBitMask = coinCategory

    ship.physicsBody?.collisionBitMask = 0
    ship.name = "ship"
    ship.position = CGPointMake(120, 160)

    self.addChild(ship)

    actionMoveUp = SKAction.moveByX(0, y: 30, duration: 0.2)
    actionMoveDown = SKAction.moveByX(0, y: -30, duration: 0.2)
}

1 个答案:

答案 0 :(得分:0)

我不喜欢将SKActions用于这些类型的东西,因为它们真的只适用于简单的动画。但是,根据游戏的要求,这可能是合适的。

如果您坚持使用SKActions而不是moveBy,那么为什么不使用moveTo利用触摸位置?你唯一需要做的就是根据你的精灵需要旅行的距离来提出一个比例,这样你的动画持续时间才是正确的。例如:

let curPoint = self.sprite.position
let destinationPoint = touch.position

let diffPoint = CGPoint(
    x: curPoint.x - destinationPoint.x,
    y: curPoint.y - destinationPoint.y
)

let distance = sqrt(pow(diffPoint.x, 2) + pow(diffPoint.y, 2))

let durationRatio = distance / CGFloat(600)

let moveAction = SKAction.moveTo(point, duration: NSTimeInterval(durationRatio))

self.sprite.runAction(moveAction, withKey: "move")

然后当你想要取消运动时。在touchesEnded你做

self.sprite.removeActionForKey("move")

使用物理速度

let curPoint = CGPoint(x: 10, y: 10)
let destinationPoint = CGPoint(x: 100, y: 100)

let diffPoint = CGPoint(
    x: curPoint.x - destinationPoint.x,
    y: curPoint.y - destinationPoint.y
)

let distance = sqrt(pow(diffPoint.x, 2) + pow(diffPoint.y, 2))

let normalizedVector = CGPoint(
    x: diffPoint.x / distance,
    y: diffPoint.y / distance
)

let speed = CGFloat(100)

let velocity = CGVector(
    dx: normalizedVector.x * speed,
    dy: normalizedVector.y * speed
)

self.sprite.physicsBody!.velocity = velocity

在touchesEnded中你做了

self.sprite.physicsBody!.velocity = CGVector(dx: 0.0, dy: 0.0)
相关问题