今天发现一个很有意思的现象。首先来看段简单的代码,主要功能就是创建一个SKShapeNode
圆形和SKSpriteNode
正方形,你们先猜猜运行效果。
func createCircle() {
backgroundColor = .orange
let path = CGMutablePath()
path.addArc(center: view!.center, radius: 40, startAngle: 0, endAngle: .pi*2, clockwise: true)
// SKShapeNode 没有锚点;怎么让圆圈固定中心点缩放???
let circle = SKShapeNode(path: path)
circle.fillColor = .blue
circle.lineWidth = 1
circle.strokeColor = .white
// 总宽度20 中间位置是strokwidth 类似模糊玻璃效果
circle.glowWidth = 5
addChild(circle)
animateNodes(circle, type: .scale)
let circle0 = SKSpriteNode(color: .green, size: CGSize(width: 100, height: 100))
circle0.position = CGPoint(x: view!.frame.midX, y: view!.frame.midY - 100.0)
// circle0.anchorPoint = CGPoint(x: 0, y: 0)
addChild(circle0)
animateNodes(circle0, type: .scale)
}
动画代码块是这样的
extension ActionScene {
// 缩放动画
func animateNodes(_ node: SKNode, type: AnimateType) {
switch type {
case .scale:
node.run(.sequence([.wait(forDuration: 0.2),
.repeatForever(.sequence([
.scale(to: 1.5, duration: 0.3),
.scale(to: 1, duration: 0.3),
.wait(forDuration: 2)]))]))
case .move:
node.run(.sequence([.wait(forDuration: 1),
.repeatForever(.sequence([.moveTo(x: 300.0, duration: 0.8),
.moveTo(x: -300.0, duration: 0.8)]))]))
case .rotation:
node.run(.sequence([.wait(forDuration: 1),
.repeatForever(.sequence([.rotate(byAngle: .pi/2, duration: 0.8),
.rotate(byAngle: -.pi/2, duration: 0.8)]))]))
}
}
}
心里有自己的效果了吗。现在公布代码运行效果:
从效果图看出如下现象:
- 正方形是沿着自身的中心点缩放的
- 圆形是分别沿x y同步缩放的
我们知道动画的变化是沿着固定点来变化的,也就是锚点anchorPoint。
通过现象得出以下初步结论:
- 正方形SKSpriteNode的anchorPoint 默认为(0.5,0.5)和positon重合,所以沿着中心点缩放
- 圆形SKShapeNode的anchorPoint默认可能为左下标原点也就是(0,0)
但是当你点anchorPoint属性时,根本就点不来,cmd+点击查看SKShapeNode类时,你会发现根本找不到anchorPoint属性,连它的父类SKNode也没有anchorPoint属性。
那要如何实现圆形和正方形一样沿着中心点缩放的效果呢???
是的,也许聪明的你应该想到了,既然SKSpriteNode
是我们想要的效果,我们能不能把SKShapeNode
类型的精灵以子node形式加到SKSpriteNode
上呢?那就开始干吧!如下代码:
func createCircle() {
backgroundColor = .orange
let circle0 = SKSpriteNode(color: .green, size: CGSize(width: 100, height: 100))
circle0.position = CGPoint(x: view!.frame.midX, y: view!.frame.midY)
// circle0.anchorPoint = CGPoint(x: 0, y: 0)
addChild(circle0)
let path = CGMutablePath()
path.addArc(center: CGPoint(x: 0, y: 0), radius: 40, startAngle: 0, endAngle: .pi*2, clockwise: true)
// SKShapeNode 没有锚点;怎么让圆圈固定中心点缩放???
let circle = SKShapeNode(path: path)
circle.fillColor = .blue
circle.lineWidth = 1
circle.strokeColor = .white
// 总宽度20 中间位置是strokwidth 类似模糊玻璃效果
circle.glowWidth = 5
// addChild(circle)
// animateNodes(circle, type: .scale)
circle0.addChild(circle)
animateNodes(circle0, type: .scale)
}
运行效果:
哇,果真可以。也许正如SKShapeNode其名,苹果只想它纯粹的画图即可,若需要其它额外的功能 就以子类的方式添加在SKSpriteNode上。
注意点
当一个node以子node添加到父node上时,有以下两注意点
- 当一个node被添加到parentNode上时,其position默认是和父position重合的
- 若移动子position,以position为中心点,往上y加,往下y减,往左x减,往右x加
例如,将上面center由之前的
CGPoint(x: 0, y: 0)
改成CGPoint(x: -40, y: 40)
运行结果为:
END