[英]Using the iPhone accelerometer to move a sprite along the x axis
I am working on an iPhone game using cocos2d. 我正在使用cocos2d开发iPhone游戏。 I am trying to use the accelerometer for movement of a sprite in portrait mode to move left and right.
我正在尝试使用加速计在纵向模式下移动精灵来左右移动。 For some reason with the code I am using it defaults to moving right UNLESS the phone is tilted at a 45 degree angle, ie the returned values are all positive(indicating it should move to the right) until it is tilted at a 45 degree angle, either left or right.
出于某些原因,我使用的代码默认为向右移动除非手机以45度角倾斜,即返回的值都是正的(表示它应该向右移动),直到它以45度角倾斜,左或右。 Dead center is returning around 600 and then decreasing the further you tilt the phone left or right until it gets to a 45 degree angle (where it hits 0 and starts to go negative).
死点中心返回600左右然后逐渐减小你向左或向右倾斜手机直到它达到45度角(它达到0并开始变为负值)。 Below is the code I am using.
以下是我正在使用的代码。 Any help would be GREATLY appreciate.
任何帮助都会非常感激。
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
#define kFilteringFactor 0.75
static UIAccelerationValue rollingX = 0, rollingY = 0, rollingZ = 0;
rollingX = (acceleration.x * kFilteringFactor) +
(rollingX * (1.0 - kFilteringFactor));
rollingY = (acceleration.y * kFilteringFactor) +
(rollingY * (1.0 - kFilteringFactor));
rollingZ = (acceleration.z * kFilteringFactor) +
(rollingZ * (1.0 - kFilteringFactor));
float accelX = rollingX;
float accelY = rollingY;
float accelZ = rollingZ;
CGSize winSize = [CCDirector sharedDirector].winSize;
#define kRestAccelX 0.6
#define kShipMaxPointsPerSec (winSize.height*0.5)
#define kMaxDiffX 0.2
float accelDiffX = kRestAccelX - ABS(accelX);
float accelFractionX = accelDiffX / kMaxDiffX;
float pointsPerSecX = kShipMaxPointsPerSec * accelFractionX;
_shipPointsPerSecX = pointsPerSecX;
NSLog(@"_shipPointsPerSecX: %f", _shipPointsPerSecX);
}
- (void)updateShipPos:(ccTime)dt {
CGSize winSize = [CCDirector sharedDirector].winSize;
float maxX = winSize.width - _ship.contentSize.width/2;
float minX = _ship.contentSize.width/2;
float newX = _ship.position.x + (_shipPointsPerSecX * dt);
newX = MIN(MAX(newX, minX), maxX);
_ship.position = ccp(newX, _ship.position.y);
// NSLog(@"newx: %f", newX);
}
Basically, what your accelerometer should do is updating the acceleration (with a filtering factor like you do). 基本上,您的加速度计应该做的是更新加速度(使用像您一样的过滤因子)。
But next to it you should maintain velocity and position, and adapt both in your scheduled step(float dt) function like this: 但旁边你应该保持速度和位置,并在你的预定步骤(浮动dt)函数中适应这样:
Velocity += acceleration*dt Position += velocity * dt 速度+ =加速度* dt位置+ =速度* dt
Do that for x and y 为x和y做那个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.