您的位置:首页 > 移动开发 > IOS开发

ios 3D引擎 SceneKit 开发(4) --关于旋转的几点问题(1)

2016-05-06 22:55 495 查看
旋转模型是经常遇到了,我们之前用CABasicAnimation 可以旋转一个view,其实它也可以旋转一个SCNNode。

首先我们要明白一个概念,每个SCNNode 都有自身的三维坐标系,用CABasicAnimation就是让SCNNode绕自身的三维坐标轴旋转,所以要特别注意是坐标轴,不是这个SCNNode的几何中心。一般SceneKit 的自带的几个几何体的坐标系原点(0,0,0)就是这个它的几何中心,比如说SCNBox;SCNSphere等等,所以看上去跟绕几何中心旋转一模一样。

我们先从Demo 入手,这里是模拟 太阳-地球-月球 天体运动的demo,分以下几点:

1, 地球,月球自转

2, 月球绕着地球转

3, 地月系统绕着太阳转

如下图:



第一点 先实现地球,月球自转

// Rotate the moon
animation = [CABasicAnimation animationWithKeyPath:@"rotation"];
animation.duration = 1.5;
animation.toValue = [NSValue valueWithSCNVector4:SCNVector4Make(0, 1, 0, M_PI * 2)];
animation.repeatCount = FLT_MAX;
[_moonNode addAnimation:animation forKey:@"moon rotation"];


其实SceneKit 框架有自己的动画API ,我们这里地球的旋转用它,让大家了解一下

[_earthNode runAction:[SCNAction repeatActionForever:[SCNAction rotateByX:0 y:2 z:0 duration:1]]];   //地球自转


从上面的代码可以看出来都是绕Y轴旋转。

第二点 月球绕着地球转(父子SCNNode技巧)

月球需要绕着地球的Y轴旋转,我们知道,只有地球才绕自己的Y轴旋转。所以我们可以让地球带着月球绕自己的Y轴旋转。很简单,将月球add 到地球上:

[_earthNode addChildNode:_moonNode];


这是就会实现月球绕着地球转的效果。

但现实中,地球的自转周期跟月球的公转周期是不一样的。所以月球不能添加到地球这个SCNNode 上,我们要重新新建一个SCNNode,位置跟地球一样,把_moonNode添加到这个新建的SCNNode上,然后旋转它。

_moonNode.position = SCNVector3Make(3, 0, 0);

// Moon-rotation (center of rotation of the Moon around the Earth)
SCNNode *moonRotationNode = [SCNNode node];

[moonRotationNode addChildNode:_moonNode];

// Rotate the moon around the Earth
CABasicAnimation *moonRotationAnimation = [CABasicAnimation animationWithKeyPath:@"rotation"];
moonRotationAnimation.duration = 1.5;
moonRotationAnimation.toValue = [NSValue valueWithSCNVector4:SCNVector4Make(0, 1, 0, M_PI * 2)];
moonRotationAnimation.repeatCount = FLT_MAX;
[moonRotationNode addAnimation:animation forKey:@"moon rotation around earth"];


第三点 地月系统绕着太阳转

这个时候地球和月球要绕着太阳转,可以把地月系统看成一个整体。我们创建一个地月系统earthGroupNode,然后将moonRotationNode 和 earthNode 添加进去:

[_earthGroupNode addChildNode:_earthNode];
[_earthGroupNode addChildNode:moonRotationNode];


太阳不自转,同理,在太阳同样的位置创建一个SCNNode,让地月系统earthGroupNode随着这个节点旋转

//离太阳的距离
_earthGroupNode.position = SCNVector3Make(10, 0, 0);


// Earth-rotation (center of rotation of the Earth around the Sun)
SCNNode *earthRotationNode = [SCNNode node];
[_sunNode addChildNode:earthRotationNode];

// Earth-group (will contain the Earth, and the Moon)
[earthRotationNode addChildNode:_earthGroupNode];

// Rotate the Earth around the Sun
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"rotation"];
animation.duration = 10.0;
animation.toValue = [NSValue valueWithSCNVector4:SCNVector4Make(0, 1, 0, M_PI * 2)];
animation.repeatCount = FLT_MAX;
[earthRotationNode addAnimation:animation forKey:@"earth rotation around sun"];


然后大体流程就结束了。然后我们可以给太阳贴图添加一些动画,让他有岩浆的效果,在加一些光效,整体就更真实了。

整体效果如下:



demo 代码已上传到github

https://github.com/pzhtpf/SceneKitRoationDemo

抛砖引玉,关于旋转持续完善中……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: