我正在尝试使用xcode 6.1和swift来构建一个游戏,其中一个关键元素就是让一个球绕圈旋转(不绕自己的轴旋转但是沿着圆形路径旋转)。我怎样才能最有效地完成这项工作?这是我试过的代码。
func rotate(){
newBall = balls(size: self.size, positionX: -36, positionY: 250)
var path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddArc(path, nil, 0, 15, 15, CGFloat(M_PI_2), CGFloat(M_PI_2), true)
newBall.node.path = path
self.addChild(newBall.node)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
rotate()
}
答案 0 :(得分:2)
有很多方法可以做到这一点。我只会告诉你一个方法
您可以复制粘贴此代码并根据需要进行修改
// add sprite to scene
let mysprite = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 10, height: 10))
mysprite.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
self.addChild(mysprite)
// the circle path's diameter
let circleDiameter = CGFloat(100)
// center our path based on our sprites initial position
let pathCenterPoint = CGPoint(
x: mysprite.position.x - circleDiameter/2,
y: mysprite.position.y - circleDiameter/2
)
// 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: true, duration: 2)
// make our sprite run this action forever
mysprite.runAction(SKAction.repeatActionForever(followCirclePath))
答案 1 :(得分:1)
我似乎记得创建明显零长度的路径并不总是有预期的结果。尝试拆分路径:
CGPathAddArc(path, nil, 0, 15, 15, CGFloat(M_PI_2), -CGFloat(M_PI_2), true)
CGPathAddArc(path, nil, 0, 15, 15, -CGFloat(M_PI_2), CGFloat(M_PI_2), true)