以特定速度在屏幕上移动对象。(精灵套件)

时间:2016-07-31 05:59:09

标签: swift sprite-kit skspritenode

我有一个需要在屏幕上上下移动的对象。第一次单击时,它会在屏幕上向下移动到持续时间为3秒的端点。您可以随时单击以阻止其向下移动,并使其开始向上移动到另一个端点,同样持续3秒。这样做的问题是,如果单击向下移动对象但是再次立即再次单击以将其向上移动,则对象向上移动但速度非常慢,因为它的持续时间为3秒。 (我希望这是有道理的)所以我想要的是停止使用持续时间来设置对象移动的速度/速度。有没有办法说空白速度转移到x.y点?谢谢。 (无论物体在何处并且必须移动到我希望它始终以相同的速度移动。)

这就是我现在用来移动物体的原因:

func moveObject(){
    let endpoint = CGPoint(x: self.size.width / 2 , y: self.size.height / 1.8888888888 )
    let moveObject = SKAction.moveTo(endpoint, duration: 3.0 )
    let moveObjectSequence = SKAction.sequence([moveLine])
    Object.runAction(moveLineSequence)
}

更正后的代码:

func dropLine(){
    if hookNumber == 1{
        let endpoint = CGPoint(x: self.size.width / 2 , y: self.size.height / 1.8888888888 )
        let moveLine = SKAction.moveTo(endpoint, duration: getDuration(fishLine.position,pointB:endpoint,speed:300.0))
        let moveLineSequence = SKAction.sequence([moveLine])
        fishLine.runAction(moveLineSequence)
    }
}

func dropHook(){
    if hookNumber == 1{
        let endpoint = CGPoint(x: self.size.width / 2 , y: self.size.height - 2030)
        let moveLine = SKAction.moveTo(endpoint, duration: getDuration(fishHook.position,pointB:endpoint,speed:300.0))
        let moveLineSequence = SKAction.sequence([moveLine])
        fishHook.runAction(moveLineSequence)
            hookNumber = 2
    }
}

func raiseLine(){
    if hookNumber == 2{
        let endpoint = CGPoint(x: self.size.width / 2 , y: 3050 )
        let moveLine = SKAction.moveTo(endpoint, duration: getDuration(fishLine.position,pointB:endpoint,speed:300.0))
        let moveLineSequence = SKAction.sequence([moveLine])
        fishLine.runAction(moveLineSequence)
    }
}

func raiseHook(){
    if hookNumber == 2{
        let endpoint = CGPoint(x: self.size.width / 2 , y: self.size.height - 3 )
        let moveLine = SKAction.moveTo(endpoint, duration: getDuration(fishHook.position,pointB:endpoint,speed:300.0))
        let moveLineSequence = SKAction.sequence([moveLine])
        fishHook.runAction(moveLineSequence)
    }
}

1 个答案:

答案 0 :(得分:2)

我认为您可以根据计算速度修改您的方法。 因此,如果您知道自己的速度,则可以计算节点到达某个点所需的时间并将速度更改为合理的值。

// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
//MARK: - Calculate action duration btw two points and speed
// #-#-#-#-#-#-#-#-#-#-#-#-#-#-#
func getDuration(pointA:CGPoint,pointB:CGPoint,speed:CGFloat)->NSTimeInterval {
    let xDist = (pointB.x - pointA.x)
    let yDist = (pointB.y - pointA.y)
    let distance = sqrt((xDist * xDist) + (yDist * yDist));
    let duration : NSTimeInterval = NSTimeInterval(distance/speed)
    return duration
}

假设您的节点速度为150.0

您的行动将是:

let moveObject = SKAction.moveTo(endpoint, duration: getDuration(node.position,pointB:endpoint,speed:150.0))

通过这种方法,你可以快速改变,并且你没有这种令人不快的缓慢。

P.S。不要忘记将大写更改为您的属性:在swift中是一种不好的态度,使用对象而不是Object。