如何为SCNAnimationPlayer配置animationDidStop监听动画播放结束?
SCNAnimation 播放状态监听实现方案
SCNAnimation的生命周期回调通过SCNAnimationDelegate协议实现,你需要将代理绑定到动画对象上,并实现对应代理方法即可监听到开始、结束事件,具体实现如下:
1. 让持有动画的类遵循SCNAnimationDelegate协议
注意遵循该协议的类必须继承自NSObject,普通Swift类需要手动指定父类,UIViewController默认已继承无需额外处理:
import UIKit import SceneKit // 示例为ViewController类,遵循SCNAnimationDelegate协议 class ViewController: UIViewController, SCNAnimationDelegate { // 你的原有类实现代码 }
2. 配置动画时绑定代理
在你原有动画配置的逻辑中,新增一行代理赋值代码即可:
var animationPlayer = animationFromSceneNamed(path: "hunt.scn")! animationPlayer.speed = 0.5 animationPlayer.animation.duration = 5 animationPlayer.animation.repeatCount = 1 animationPlayer.animation.isRemovedOnCompletion = false // 新增:将动画的代理绑定到当前实例 animationPlayer.animation.delegate = self hunts[0].nodeC.addAnimationPlayer(animationPlayer, forKey: nil)
3. 实现代理方法监听事件
// 动画开始播放时触发 @objc func animationDidStart(_ anim: SCNAnimation) { print("动画已启动") } // 动画停止时触发,finished参数标识是否为正常播放完成 @objc func animationDidStop(_ anim: SCNAnimation, finished: Bool) { if finished { print("动画正常播放结束,可在此处执行后续逻辑") } else { print("动画被中途终止") } }
常见不触发原因排查
- 不要把代理绑定到
SCNAnimationPlayer实例上,必须绑定到animationPlayer.animation的delegate属性 - 代理方法必须加
@objc前缀,否则不会被回调触发 - 如果同一个节点添加了多个动画,可以给
addAnimationPlayer的forKey参数传入唯一标识,在代理方法中对比anim参数匹配对应动画
内容的提问来源于stack exchange,提问作者Hope
相关产品推荐
相关产品推荐

