如果您绘制已生成的图8,则会看到您的精灵只在底部圆圈之后,因为这是您绘制路径的方式。
您需要画出顶部或底部圆的一半,从顶部/底部到中间,然后添加从中间开始和结束的完整另一个圆,最后再添加另一个半圆回到您开始的位置。
下面是一个例子,这也吸引了边框和8字型道路可走:
class GameScene: SKScene {
// var sprite = SKSpriteNode()
var figureEightPath = CGMutablePath()
override func didMove(to view: SKView) {
let boundingRect = CGRect(x: -200, y: -400, width: 400, height: 800)
addChild(drawSKShapeNode(fromRect: rect, withWidth: 2, inColour: SKColor.green, called: "rect"))
figureEightPath = drawFigureEight(in: boundingRect)
addChild(drawSKShapeNode(fromPath: figureEightPath, withWidth: 2, inColour: SKColor.red, called: "path"))
let sprite = SKSpriteNode(color: SKColor.yellow, size: CGSize(width: 50, height: 50))
addChild(sprite)
let moveAction = SKAction.follow(figureEightPath, asOffset: false, orientToPath: true, speed: 200)
sprite.run(SKAction.repeatForever(moveAction))
}
func drawSKShapeNode(fromPath path: CGMutablePath,
withWidth width: CGFloat,
inColour colour: SKColor,
called name: String) -> SKShapeNode {
let shape = SKShapeNode(path: path, centered: true)
shape.lineWidth = width
shape.strokeColor = colour
shape.name = name
return shape
}
func drawSKShapeNode(fromRect rect: CGRect,
withWidth width: CGFloat,
inColour colour: SKColor,
called name: String) -> SKShapeNode {
let shape = SKShapeNode(rect: rect)
shape.lineWidth = width
shape.strokeColor = colour
shape.name = name
return shape
}
func drawFigureEight(in rect: CGRect) -> CGMutablePath {
let bottomCentre = CGPoint(x: rect.midX, y: rect.height/4+rect.minY)
let topCentre = CGPoint(x: rect.midX, y:(rect.height/4)*3+rect.minY)
let radius = rect.height/4
let bottom = CGPoint(x: rect.midX, y: rect.minY)
let path = CGMutablePath()
path.move(to: bottom)
//Draw a semi-circle from the bottom counter-clockwise to the middle
path.addArc(center: bottomCentre, radius: radius, startAngle: CGFloat(Double.pi*1.5), endAngle: CGFloat(Double.pi/2), clockwise: false)
//Draw to top circle in a clockwise direction
path.addArc(center: topCentre, radius: radius, startAngle: CGFloat(Double.pi*1.5), endAngle: CGFloat(-Double.pi/2), clockwise: true)
//Draw the rest of the bottom circle by drawing a semi-circle from the middle to the bottom counter-clockwise.
path.addArc(center: bottomCentre, radius: radius, startAngle: CGFloat(Double.pi/2), endAngle: CGFloat(-Double.pi/2), clockwise: false)
return path
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
有几个辅助函数的 - drawSKShapeNode - 你将不再需要,但有用调试,因为他们通过创建SKShapeNode来绘制CGPath或CGRect。
现在有很多意义。我刚刚用你的建议代替了我的代码,完美地工作。非常感谢你的详细解答史蒂夫! –
精灵按照绘制路径的顺序跟随路径。在你最初的例子中,当它到达其中一个圆圈的底部时,它没有到达顶部圆圈的路径,所以它停止了。 –