首页 > 代码库 > SpriteKit代码动态调整sks文件中粒子的颜色
SpriteKit代码动态调整sks文件中粒子的颜色
在Xcode中我们可以很方便的使用粒子模板制作粒子,然后保存为sks文件,这样我们随时就可以在代码中使用它们了:
if let fireParticles = SKEmitterNode(fileNamed: "FireParticles"){
//do anything you want!!!
}
我们想要制作的效果是当小球调入时间空隙时显示被吞噬的粒子效果,不过sks文件中的粒子消逝效果是粉色烟雾的,但是小球有7种颜色:
我当然可以依次制作7个sks粒子文件对应每个球的颜色,但显然这违反了KISS原则.更好的做法是用代码调整不同颜色的小球消逝时产生对应颜色的烟雾,而不是都是粉色滴,那么单调 ;(
我们打开Xcode的粒子编辑器界面,可以发现其中有一个Color Ramp属性:
它对应于粒子对象的particleColor的属性,如果我们直接在代码中修改它可以实现改变粒子颜色吗?答案是:不可以!
原因在此:
The particleColor property isn‘t working because of the color ramp settings in the Particle Editor. These are actually stored in the particleColorSequence, which ignores all other particle color properties.
So, to make it work, you need to override the particleColorSequence setter and make it nil first. Then, you need to set the particleColorBlendFactor to fully blend your chosen color with the particle texture (full blending is 1.0). From then on, any explicit particle color setting should work:
emitter.particleColorSequence = nil;
emitter.particleColorBlendFactor = 1.0;
emitter.particleColor = [SKColor redColor];
各位看官都很清楚了吧?如果少数不明所以的吃瓜群众一脸朦胧状,请跟帖或私信 ;)
上面是Objc的代码,我们把它改为Swift:
//["ballBlue","ballCyan","ballGreen","ballGrey","ballPurple","ballRed","ballYellow"]
func destroyBall(_ ball:SKNode){
if let fireParticles = SKEmitterNode(fileNamed: "FireParticles"){
fireParticles.position = ball.position
let imageName = ball.userData!["imageName"] as! String
var particelColor:UIColor
switch imageName {
case "ballBlue":
particelColor = .blue
case "ballCyan":
particelColor = .cyan
case "ballGreen":
particelColor = .green
case "ballGrey":
particelColor = .gray
case "ballPurple":
particelColor = .purple
case "ballRed":
particelColor = .red
case "ballYellow":
particelColor = .yellow
default:
fatalError("非法的颜色名称!!!")
}
fireParticles.particleColorSequence = nil
fireParticles.particleColorBlendFactor = 1.0
fireParticles.particleColor = particelColor
addChild(fireParticles)
}
ball.removeFromParent()
}
哦了!我们成功的完成了题目的要求(gif动图加载较慢):
SpriteKit代码动态调整sks文件中粒子的颜色
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。