如何在SKAction中途反转Sprite所遵循的路径方向? [英] How to reverse the direction of path followed by sprite in an SKAction midway?

查看:44
本文介绍了如何在SKAction中途反转Sprite所遵循的路径方向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  // 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()来反转子画面的方向,但这只能从起点开始执行。

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

推荐答案

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

 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()

这些基本上将您的人定义为SKSpriteNode()您的路径为UIBezierPath()等等。当然,您将在didMoveToView下使用Person.position = positionPerson = SKSpriteNode(imageNamed: "name")来创建子画面。

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

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是否为假(这是因为它没有发生任何事情,并且它刚刚加载),并运行moveClockway函数并将move顺时针bool设置为True,并将GameStarted bool设置为True。其他一切都是不言而喻的。

这篇关于如何在SKAction中途反转Sprite所遵循的路径方向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆