如何使用SKAction垂直移动我的游戏怪物

时间:2016-03-16 10:55:23

标签: swift sprite-kit

我是一个慢慢学习swift和Xcode功能的初学者,截至目前我仍然遇到类似这样的简单问题:

 func addMonster() {

    // Create sprite
    let monster = SKSpriteNode(imageNamed: "Enemy")

    // Determine where to spawn the monster along the Y axis
    let actualY = random(min: monster.size.height/2, max: size.height - monster.size.height/2)

    // Position the monster slightly off-screen along the right edge,
    // and along a random position along the Y axis as calculated above
    monster.position = CGPoint(x: size.width + monster.size.width/2, y: actualY)

    // Add the monster to the scene
    addChild(monster)

    // Determine speed of the monster
    let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0))

    // Create the actions
    let actionMove = SKAction.moveTo(CGPoint(x: -monster.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
    let actionMoveDone = SKAction.removeFromParent()
    monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))

}

请帮我垂直移动我的怪物而不是水平移动

2 个答案:

答案 0 :(得分:0)

保持不变x坐标并更改y坐标

let actionMove = SKAction.moveTo(CGPoint(x: actualX, y: -monster.size.height/2), duration: NSTimeInterval(actualDuration)
let actionMoveDone = SKAction.removeFromParent() monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))

答案 1 :(得分:0)

主要将“width”更改为“height”,将“height”更改为“width”。并定义actualX

func addMonster() {

    // Create sprite
    let monster = SKSpriteNode(imageNamed: "Enemy")

    // Determine where to spawn the monster along the Y axis
    let actualX = random(min: monster.size.width/2, max: size.width - monster.size.width/2)

    // Position the monster slightly off-screen along the right edge,
    // and along a random position along the Y axis as calculated above
    monster.position = CGPoint(x: actualX, y: size.height + monster.size.height/2)

    // Add the monster to the scene
    addChild(monster)

    // Determine speed of the monster
    let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0))

    // Create the actions
    let actionMove = SKAction.moveTo(CGPoint(x:actualX, y: -monster.size.height/2), duration: NSTimeInterval(actualDuration))
    let actionMoveDone = SKAction.removeFromParent()
    monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))

}