Center SKSpriteNode during pinch

为君一笑 提交于 2019-12-11 10:35:19

问题


I have implemented zoom/pinch on my SKScene with the selected answer in this thread:

Zooming an SKNode inconsistent

I am now attempting to get the hero character to stay centered (smoothly) during a pinch or zoom action because if I don't, the heroNode will disappear off the screen quickly. I have a centerHero method which I can call when I want, and it works quite well, but when I call this method at the end of the pinch handler the effect is very, very jerky. Here is the pinch handler:

- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer
{
    [map runAction:[SKAction scaleBy:recognizer.scale duration:0]];
    recognizer.scale = 1;

    // While zooming/pinching, make sure hero is centered:
    [self centerHero];
}

and here is the center hero method:

- (void)centerHero
{
    CGFloat centerX = self.view.bounds.size.width/2;
    CGFloat centerY = self.view.bounds.size.height/2;

    CGFloat heroX = [self.heroNode parent].position.x;
    CGFloat heroY = [self.heroNode parent].position.y;

    CGPoint heroPoint = CGPointMake(heroX, heroY);
    CGPoint newHeroPoint = [self convertPoint:heroPoint fromNode:map];

    CGFloat newHeroX = newHeroPoint.x;
    CGFloat newHeroY = newHeroPoint.y;

    CGFloat xDiff = centerX - newHeroX;
    CGFloat yDiff = centerY - newHeroY;

    SKAction *moveBy = [SKAction moveByX:xDiff y:yDiff duration:5];
    [map runAction:moveBy];
}

Any suggestions on how to make this "auto-centering" smooth?


回答1:


It looks as though you are scaling the map node, rather than the scene itself. When you scale the node, it will zoom to the anchor point of that node, instead of simply zooming in to the centre of the visible area.

If you scale the scene itself it should scale everything properly, e.g.:

[self runAction:[SKAction scaleBy:recognizer.scale duration:0]];

Assuming you're running this action from within the SKScene. You could also try:

[map.scene runAction:[SKAction scaleBy:recognizer.scale duration:0]];

...which would also point to the parent scene the map belongs to.



来源:https://stackoverflow.com/questions/19922792/center-skspritenode-during-pinch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!