简体   繁体   English

Cocos2D-使精灵平滑跟随并旋转以触摸

[英]Cocos2D - Make sprite smoothly follow & rotate to touch

I'm trying to make a sprite to smoothly follow & rotate according to touch on the screen. 我正在尝试制作一个精灵,以根据屏幕上的触摸平稳地跟随和旋转。 The player is not forced to touch on the sprite itself to make it move, as he can only control one sprite at a time. 玩家不必被迫触摸精灵本身以使其移动,因为他一次只能控制一个精灵。 So wherever the touch is on the screen, the player must follow the movement. 因此,无论屏幕上的触摸位置如何,玩家都必须跟随运动。 Here's what I have so far : 这是我到目前为止的内容:

In GameScene.m : 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;
}

And here's Player.m : 这是Player.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;   

}

This code works well, but the rotation is not smooth at all, mainly when the player moves his finger slowly on the screen, the sprite goes crazy! 这段代码效果很好,但是旋转一点也不平滑,主要是当玩家在屏幕上缓慢移动手指时,精灵会发疯! I tried many things, like setting up actions, but the touchMoved method is called too rapidly to use Actions. 我尝试了很多事情,例如设置动作,但是touchMoved方法被调用得太快而无法使用动作。

What should I do to solve this? 我该怎么做才能解决这个问题? Thanks a lot! 非常感谢!

One option is to use a Physics Engine (chipmunk, box2d, ...) and have a damped spring between your finger position and your sprite. 一种选择是使用物理引擎(花栗鼠,box2d等),并在手指位置和子画面之间设置阻尼弹簧。

If you can't afford a physics engine in your game, and you want a smooth real-life like movement, you should keep the sprite position, velocity and acceleration (idem for angle, angular velocity, angular acceleration). 如果您的游戏负担不起物理引擎的费用,并且想要像运动一样平稳的现实生活,则应保留子画面的位置,速度和加速度(角度,角速度,角加速度的理想值)。 Your finger movement will then update the accelerations (like a spring would do), and you then start a scheduler to update the velocity and position 60 times/second. 然后您的手指移动将更新加速度(就像弹簧一样),然后启动调度程序以60次/秒的速度更新速度和位置。

That's how I'd do it 我就是那样做的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM