我遇到了 HelloWorldLayer 类的更新问题:在我的 iPad 上构建和运行应用程序时未调用方法。
不太确定问题是什么,因为 init: 和 accelerometer: didAccelerate: 按预期调用。
下面是 HelloWorldLayer 的实现:
// Import the interfaces
#import "HelloWorldLayer.h"
// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
const float MaxPlayerAccel = 400.0f;
const float MaxPlayerSpeed = 200.0f;
#pragma mark - HelloWorldLayer
// HelloWorldLayer implementation
@implementation HelloWorldLayer
{
CGSize _winSize;
CCSprite *_playerSprite;
UIAccelerationValue _accelerometerX;
UIAccelerationValue _accelerometerY;
float _playerAccelX;
float _playerAccelY;
float _playerSpeedX;
float _playerSpeedY;
}
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
- (id)init
{
if (self = [super initWithColor:ccc4(94, 63, 107, 255)])
{
_winSize = [CCDirector sharedDirector].winSize;
_playerSprite = [CCSprite spriteWithFile:@"Player-hd.png"];
_playerSprite.position = ccp(_winSize.width - 50.0f, 50.0f);
[self addChild:_playerSprite];
self.accelerometerEnabled = YES;
NSLog(@"init: method executed");
}
return self;
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
const double FilteringFactor = 0.75;
_accelerometerX = acceleration.x * FilteringFactor + _accelerometerX * (1.0 - FilteringFactor);
_accelerometerY = acceleration.y * FilteringFactor + _accelerometerY * (1.0 - FilteringFactor);
if (_accelerometerY > 0.05)
{
_playerAccelX = -MaxPlayerAccel;
}
else if (_accelerometerY < 0.05)
{
_playerAccelX = MaxPlayerAccel;
}
if (_playerAccelX < -0.05)
{
_playerAccelY = -MaxPlayerAccel;
}
else if (_playerAccelX > -0.05)
{
_playerAccelY = MaxPlayerAccel;
}
}
- (void)update:(ccTime)dt
{
NSLog(@"update: method is being called");
// 1
_playerSpeedX += _playerAccelX * dt;
_playerSpeedY += _playerAccelY * dt;
// 2
_playerSpeedX = fmaxf(fminf(_playerSpeedX, MaxPlayerSpeed), - MaxPlayerSpeed);
_playerSpeedY = fmaxf(fminf(_playerSpeedY, MaxPlayerSpeed), - MaxPlayerSpeed);
// 3
float newX = _playerSprite.position.x + _playerSpeedX * dt;
float newY = _playerSprite.position.y + _playerSpeedY * dt;
// 4
newX = MIN(_winSize.width, MAX(newX, 0));
newY = MIN(_winSize.height, MAX(newY, 0));
_playerSprite.position = ccp(newX, newY);
}
@end