我想在SceneKit中创建步行人动画。我从3DSMax + OpenCollada导出动画。dae文件,我也使用ConvertToXcodeCollada将所有动画合并在一起。如何获得动画:
SCNScene *humanScene = [SCNScene sceneNamed:@"art.scnassets/myScene.DAE"];
CAAnimation *Animation = [[humanScene rootNode] animationForKey:@"myScene-1"];
我也尝试从"SCNSceneSource"获得动画
如何添加动画:
SCNNode *humanNode = [humanScene.rootNode childNodeWithName:@"myScene-1" recursively:YES];
[humanNode addAnimation:walkingAnimation forKey:@"myScene-1"];
或:
SCNNode* humanNode = [SCNNode new];
for(SCNNode* node in humanScene.rootNode.childNodes){
[humanNode addChildNode:node];
}
[humanNode addAnimation:walkingAnimation forKey:@"myScene-1"];
我的对象"walkingAnimation"是"CAAnimationGroup"。
但是它在应用程序中没有动画。我只能在Xcode sceneKit编辑器中看到动画。
我的。dae文件的例子
用您的模型尝试下面的代码。它的工作原理。我在macOS 12.1中使用了Xcode 13.2.1。
首次填充viewDidLoad
法:
#import "GameViewController.h"
@implementation GameViewController
SCNView *sceneView;
bool notRunningSwitch;
NSMutableDictionary<NSString*, CAAnimation*> *animations;
SCNNode *node;
- (void)viewDidLoad
{
[super viewDidLoad];
sceneView = (SCNView *)self.view;
notRunningSwitch = YES;
animations = @{}.mutableCopy;
node = [SCNNode node];
SCNScene *scene = [SCNScene scene];
sceneView.scene = scene;
sceneView.autoenablesDefaultLighting = YES;
sceneView.allowsCameraControl = YES;
[self anime];
}
然后anime
和loadAnime
方法:
- (void)anime
{
SCNScene *standStillScene = [SCNScene sceneNamed:@"art.scnassets/Idle"];
for (SCNNode *childNode in standStillScene.rootNode.childNodes)
{
[node addChildNode:childNode];
}
node.scale = SCNVector3Make(0.1, 0.1, 0.1);
node.position = SCNVector3Make(0, 0,-2.5);
[sceneView.scene.rootNode addChildNode: node];
[self loadAnime:@"running" inScene:@"art.scnassets/Running" withID:@"Running-1"];
}
- (void)loadAnime:(NSString*)withKey inScene:(NSString*)scene withID:(NSString*)id
{
NSURL *url = [NSBundle.mainBundle URLForResource:scene withExtension:@"usdz"];
SCNSceneSource *source = [SCNSceneSource sceneSourceWithURL:url options:Nil];
CAAnimation *charAnimation = [source entryWithIdentifier:id
withClass:CAAnimation.self];
charAnimation.repeatCount = 1;
charAnimation.fadeInDuration = 1;
charAnimation.fadeOutDuration = 1;
[animations setValue:charAnimation forKey:withKey];
}
最后touchesBegan
:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
CGPoint point = [touches.allObjects.firstObject locationInView: sceneView];
NSDictionary<SCNHitTestOption, id> *options = @{ SCNHitTestBoundingBoxOnlyKey: @(YES) };
NSArray<SCNHitTestResult *> *hitTestResults = [sceneView hitTest: point options: options];
if (notRunningSwitch == YES) {
[sceneView.scene.rootNode addAnimation:animations[@"running"] forKey:@"running"];
} else {
[sceneView.scene.rootNode removeAnimationForKey:@"running" blendOutDuration:1.0];
}
notRunningSwitch = !notRunningSwitch;
NSLog(@"%@", hitTestResults.firstObject.node.name);
NSLog(@"%f", hitTestResults.firstObject.modelTransform.m43);
}
@end