以下代码使用了三个新的“设计参数”:减速度 速率,加速计敏感度和最大速度。
减速是通过降低当前速度值来实现的。在降低速度值以后,要将新的加速度值和加速计敏感度值相乘所得的值与降低后的速度值相加。减速度速率越小,主角精灵就能越快的改变蜘蛛的方向。加速计敏感度的值越大,主角精灵对加速计的输入就越敏感。因为这三个参数一起影响着同一个值,所以在调整的时候要注意每次只调整一个值。
在layer的init加入
[self scheduleUpdate];
player是玩家的精灵,playervelocity
-(void) update:(ccTime) delta
{
CGPoint pos = player.position;
pos.x += playervelocity.x;
CGSize screenSize = [[CCDirector sharedDirector] winSize];
float imageWidthHalved = [player texture].contentSize.width*0.5f;
float leftBorderLimit = imageWidthHalved;
float rightBorderLimit = screenSize.width-imageWidthHalved;
if(pos.x<leftBorderLimit){
pos.x = leftBorderLimit;
playervelocity = CGPointZero;
}else if(pos.x>rightBorderLimit){
pos.x = rightBorderLimit;
playervelocity = CGPointZero;
}
player.position = pos;
}
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
// 控制减速的速率
float deceleration = 0.4f;
// 加速计敏感的值越大,主教精灵对加速计的输入就越敏感
float sensitivity = 6.0f;
// 最大速度值
float maxVelocity = 100;
playervelocity.x = playervelocity.x*deceleration + acceleration.x*sensitivity;
if (playervelocity.x>maxVelocity) {
playervelocity.x = maxVelocity;
}else if(playervelocity.x<-maxVelocity){
playervelocity.x = -maxVelocity;
}
CGPoint pos = player.position;
pos.x = acceleration.x * 10;
player.position = pos;
}
{
CGPoint pos = player.position;
pos.x += playervelocity.x;
CGSize screenSize = [[CCDirector sharedDirector] winSize];
float imageWidthHalved = [player texture].contentSize.width*0.5f;
float leftBorderLimit = imageWidthHalved;
float rightBorderLimit = screenSize.width-imageWidthHalved;
if(pos.x<leftBorderLimit){
pos.x = leftBorderLimit;
playervelocity = CGPointZero;
}else if(pos.x>rightBorderLimit){
pos.x = rightBorderLimit;
playervelocity = CGPointZero;
}
player.position = pos;
}
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
// 控制减速的速率
float deceleration = 0.4f;
// 加速计敏感的值越大,主教精灵对加速计的输入就越敏感
float sensitivity = 6.0f;
// 最大速度值
float maxVelocity = 100;
playervelocity.x = playervelocity.x*deceleration + acceleration.x*sensitivity;
if (playervelocity.x>maxVelocity) {
playervelocity.x = maxVelocity;
}else if(playervelocity.x<-maxVelocity){
playervelocity.x = -maxVelocity;
}
CGPoint pos = player.position;
pos.x = acceleration.x * 10;
player.position = pos;
}
原创文章,转载请注明: 转载自小黑米的生活
本文链接地址: [cocos2d] 加速计的使用