【问题标题】:How to reverse the direction of path followed by sprite in an SKAction midway?如何在 SKAction 中途反转精灵跟随的路径方向?
【发布时间】:2015-09-19 09:02:05
【问题描述】:

我有一个使用 SKAction 沿圆形路径移动的 SKSpriteNode:

  // create the path our sprite will travel along
  let circlePath = CGPathCreateWithEllipseInRect(CGRect(origin: pathCenterPoint, size: CGSize(width: circleDiameter, height: circleDiameter)), nil)

  // create a followPath action for our sprite
  let followCirclePath = SKAction.followPath(circlePath, asOffset: false, orientToPath: false, duration: 2

我可以添加 .ReversedAction() 来反转精灵的方向,但这只会从起点发生。

当精灵位于路径中的某个点时,如何反转精灵的方向?

【问题讨论】:

    标签: ios swift sprite-kit sprite


    【解决方案1】:

    我假设你试图让它在玩家触摸屏幕时朝相反的方向移动。尝试为这两个方向创建一个函数,一个用于顺时针和逆时针在这些函数中添加您制作路径的方法。我将使用此代码来完成此任务,因为我没有发现任何错误:

     func moveClockWise() {
    
        let dx = Person.position.x - self.frame.width / 2
        let dy = Person.position.y - self.frame.height / 2
    
        let rad = atan2(dy, dx)
    
        let Path = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
        let follow = SKAction.followPath(Path.CGPath, asOffset: false, orientToPath: true, speed: 200)
        Person.runAction(SKAction.repeatActionForever(follow).reversedAction())
    
    }
    

    这只是我的首选方式,对于逆时针方向,只需创建另一个函数,只需反转代码即可。

    现在在 didMoveToView 上面添加这些变量:

    var Person = SKSpriteNode()
    
    var Path = UIBezierPath()
    
    var gameStarted = Bool()
    
    var movingClockwise = Bool()
    

    这些基本上将您的 Person 定义为 SKSpriteNode() 您的 Path 定义为 UIBezierPath() 等。当然,您可以在 didMoveToView 下使用 Person.position = positionPerson = SKSpriteNode(imageNamed: "name") 来创建精灵。

    在此之后,在override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 下,您想使用gameStarted bool 变量来检测它是否正在运行,如果将bool 设置为true 并改变它的方向。

    if gameStarted == false {
    
            moveClockWise()
            movingClockwise = true
            gameStarted = true
    
        }
        else if gameStarted == true {
    
            if movingClockwise == true {
    
                moveCounterClockWise()
                movingClockwise = false
    
            }
            else if movingClockwise == false {
    
                moveClockWise()
                movingClockwise = true
    
            }
        }
    

    基本上第一行代码检查 bool 是否为假(这是因为它没有发生任何事情并且它刚刚加载),并运行 moveClockwise 函数并将 moveClockwise bool 设置为 true 并将 gameStarted bool 设置为 true以及。其他一切都非常不言自明。

    【讨论】:

    • 是否有另一种不使用 .reverseAction() 来改变方向的方法?因为这就是给我带来问题的原因:/
    • 你能告诉我你的代码有错误吗?否则我不知道还有什么办法。
    猜你喜欢
    • 2014-09-22
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2012-01-03
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多