我已经在ios5的cocos2d框架上读了几天书,并开发了一本小书,让你了解这本书。要在此游戏中控制精灵,请使用加速度计:
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
float deceleration = 0.4f;
float sensitivity = 6.0f;
float maxVelocity = 100;
// adjust velocity based on current accelerometer acceleration
playerVelocity.x = playerVelocity.x * deceleration + acceleration.x * sensitivity;
// we must limit the maximum velocity of the player sprite, in both directions (positive & negative values)
if (playerVelocity.x > maxVelocity)
{
playerVelocity.x = maxVelocity;
}
else if (playerVelocity.x < -maxVelocity)
{
playerVelocity.x = -maxVelocity;
}
// Alternatively, the above if/else if block can be rewritten using fminf and fmaxf more neatly like so:
// playerVelocity.x = fmaxf(fminf(playerVelocity.x, maxVelocity), -maxVelocity);
}
现在我想知道我是否可以更改此代码以允许精灵沿x轴仍然加速/减速,但是使用触摸输入而不是加速度计,并且按住触摸的时间越长越快?因此,向右触摸会将精灵缓慢移动到该位置,如果触摸被释放,它将停止移动到该位置。按下触摸的时间越长,精灵移动得越快。
框架中有什么东西允许我实现一个旋转机制,允许我的精灵旋转到触摸所在的位置,所以看起来它面向被触摸的点吗?
答案 0 :(得分:1)
好吧,afaik没有确定触摸角度的方法,然后相应地旋转精灵,但如果你有精灵的x和y坐标和触摸,你可以很容易地自己计算。
CGPoint spriteCenter; // this should represent the center position of the sprite
CGPoint touchPoint; //location of touch
float distanceX = touchPoint.x - spriteCenter.x;
float distanceY = touchPoint.y - spriteCenter.y;
float angle = atan2f(distanceY,distanceX); // returns angle in radians
// do whatever you need to with the angle
一旦你有角度,你可以设置精灵的旋转。