Created
January 25, 2015 03:40
-
-
Save afjk/1b58fd39f99f49be5453 to your computer and use it in GitHub Desktop.
iOS cocos3d cameraを端末の姿勢に合わせて制御する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <CoreMotion/CoreMotion.h> | |
-(void) initMotionManager{ | |
// 1.CMMotionManagereより、端末の姿勢情報を取得 | |
_motionManager = [[CMMotionManager alloc] init]; | |
// 更新の間隔を設定する | |
_motionManager.deviceMotionUpdateInterval = 1.0f / 30.0f; | |
// ハンドラを設定する | |
CMDeviceMotionHandler deviceMotionHandler; | |
deviceMotionHandler = ^ (CMDeviceMotion* motion, NSError* error) { | |
// 2.姿勢情報をx軸90度回転して適用 | |
CMQuaternion quaternion = motion.attitude.quaternion; | |
CC3Vector4 camQuaternion; | |
camQuaternion.w = quaternion.w; | |
camQuaternion.x = -quaternion.x; | |
camQuaternion.y = -quaternion.z; | |
camQuaternion.z = quaternion.y; | |
camQuaternion = [self multiplyQuaternion:camQuaternion onAxis:CC3Vector4Make(1, 0, 0, 0) byDegress:90]; | |
self.activeCamera.quaternion = camQuaternion; | |
// 3.landscape Rightの場合、カメラをz軸回転 | |
self.activeCamera.rotation = cc3v(self.activeCamera.rotation.x, | |
self.activeCamera.rotation.y, | |
self.activeCamera.rotation.z-90); | |
}; | |
// 向きの更新通知を開始する | |
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] | |
withHandler:deviceMotionHandler]; | |
} | |
-(CC3Vector4)multiplyQuaternion:(CC3Vector4)q2 onAxis:(CC3Vector4)axis byDegress:(float)degrees{ | |
CC3Vector4 q1; | |
q1.x = axis.x; | |
q1.y = axis.y; | |
q1.z = axis.z; | |
// Converts the angle in degrees to radians. | |
float radians = CC_DEGREES_TO_RADIANS(degrees); | |
// Finds the sin and cosine for the half angle. | |
float sin = sinf(radians * 0.5); | |
float cos = cosf(radians * 0.5); | |
// Formula to construct a new Quaternion based on direction and angle. | |
q1.w = cos; | |
q1.x = q1.x * sin; | |
q1.y = q1.y * sin; | |
q1.z = q1.z * sin; | |
// Multiply quaternion, q1 x q2 is not equal to q2 x q1 | |
CC3Vector4 newQ; | |
newQ.w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z; | |
newQ.x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y; | |
newQ.y = q1.w * q2.y - q1.x * q2.z + q1.y * q2.w + q1.z * q2.x; | |
newQ.z = q1.w * q2.z + q1.x * q2.y - q1.y * q2.x + q1.z * q2.w; | |
return newQ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment