How can I use the accelemetor to move my ccpsprite/image to the left and right? (like in doodle jump)
I tried to use the开发者_高级运维 code from http://github.com/haqu/tweejump but it's not smooth...it makes 10-20px teleports :(.
Is there a better way?
Some code would be great.
Thank you very much!
:)
PS: I'm using cocos2d.
Calculate the desired velocity of your sprite as a function of accelerometer measurement.
The simplest way is to use linear dependence:
spriteVel = cft*accValue
,
where cft is some coefficient showing how fast will your sprite move
Another way is to say that acceleration of your sprite is a linear function of accelerometer measurement:
spriteAcc = cft*accValue
and the to calculate velocity as a linear function of acceleration:
spriteVel = spriteInitVel + time*accValue
That can be easy implemented in your tick
function wich is called every frame in the game like this:
`spriteVel += timeSinceLastCall*accValue'
Also in this function update the position of the sprite like this:
spritePos = timeSinceLastCall*spriteVel
That will produce a smooth and realistic (if using the second approach) sprite movement
To enable accelerometer add this code at your layer init method
isAccelerometerEnabled = YES;
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(TIMER_INTERVAL)];
where TIMER_INTERVAL is a required for you interval (1./30 for example)
implement this function in your layer too to save the accelerometer measures
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate: (UIAcceleration*)acceleration{
}
It is also possible to update sprite acceleration/velocity/position in this function
EDIT:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAcceleration_Class/Reference/UIAcceleration.html
- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate: (UIAcceleration*)acceleration{
}
just take the acceleration vector from acceleration variable
for example x:
float accX = [acceleration x];
精彩评论