gpt4 book ai didi

ios - Cocos2D - 使 Sprite 平滑地跟随和旋转触摸

转载 作者:行者123 更新时间:2023-12-01 16:48:01 27 4
gpt4 key购买 nike

我正在尝试使 Sprite 根据屏幕上的触摸平滑地跟随和旋转。玩家不必被迫触摸 Sprite 本身以使其移动,因为他一次只能控制一个 Sprite 。因此,无论触摸在屏幕上的何处,玩家都必须跟随移动。这是我到目前为止所拥有的:

GameScene.m :

- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

lastTouchLocation = location;

return YES;
}

- (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];

//moveBy determine the translate vector
CGPoint moveBy = ccpSub(lastTouchLocation, location);
[player moveBy:moveBy];

lastTouchLocation = location;
}

这里是 播放器.m :
- (float) calculateAngleForNextPoint:(CGPoint) point
{
CGPoint nextPoint = point;
CGPoint pos = self.position;

float offX = nextPoint.x - pos.x;
float offY = nextPoint.y - pos.y;

float angle = atan2f(offY, offX);
angle = CC_RADIANS_TO_DEGREES(angle);
angle = -angle + 90;

return angle;
}

- (void) moveBy:(CGPoint)_pos
{
CGPoint newPos = ccpSub(self.position, _pos);
float angle = [self calculateAngleForNextPoint:newPos];

self.position = newPos;
self.rotation = angle;

}

这段代码运行良好,但旋转一点也不流畅,主要是当玩家在屏幕上缓慢移动手指时, Sprite 会发疯!我尝试了很多东西,比如设置 Action ,但是 touchMoved 方法调用太快而无法使用 Action 。

我应该怎么做才能解决这个问题?非常感谢!

最佳答案

一种选择是使用物理引擎(花栗鼠、box2d、...)并在您的手指位置和 Sprite 之间设置一个阻尼 Spring 。

如果您在游戏中买不起物理引擎,并且想要流畅的逼真运动,则应保留 Sprite 的位置、速度和加速度(角度、角速度、角加速度同上)。然后,您的手指移动将更新加速度(就像 Spring 一样),然后您启动调度程序以 60 次/秒的速度更新速度和位置。

我就是这样做的

关于ios - Cocos2D - 使 Sprite 平滑地跟随和旋转触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445766/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com