Изменить Sprite Anchorpoint, не перемещая его? - PullRequest
5 голосов
/ 19 января 2010

Я пытаюсь изменить свою точку привязки Sprite, чтобы я мог вращаться на 0,0f, 0,0f anchorpoint.Сначала мой объект - это вращение в точке привязки по умолчанию (0.5f, 0.5f).Однако позже мне нужно, чтобы он вращался над 0,0,0.0 AnchorPoint.

Проблема в том, что я не могу изменить опорную точку и соответственно изменить положение, поэтому она остается на той же позиции, при этом объект не может быстро перемещаться и перемещаться в исходную точку.есть ли способ установить точку привязки и положение моего спрайта сразу, не двигаясь вообще?Спасибо.

-Оскар

Ответы [ 4 ]

3 голосов
/ 30 апреля 2011

Я нашел решение для этого с помощью UIView в другом месте и переписал его для cocos2d:

- (void)setAnchorPoint:(CGPoint)anchorPoint forSprite:(CCSprite *)sprite
{
    CGPoint newPoint = CGPointMake(sprite.contentSize.width * anchorPoint.x, sprite.contentSize.height * anchorPoint.y);
    CGPoint oldPoint = CGPointMake(sprite.contentSize.width * sprite.anchorPoint.x, sprite.contentSize.height * sprite.anchorPoint.y);

    newPoint = CGPointApplyAffineTransform(newPoint, [sprite nodeToWorldTransform]);
    oldPoint = CGPointApplyAffineTransform(oldPoint, [sprite nodeToWorldTransform]);

    CGPoint position = sprite.position;

    position.x -= oldPoint.x;
    position.x += newPoint.x;

    position.y -= oldPoint.y;
    position.y += newPoint.y;

    sprite.position = position;
    sprite.anchorPoint = anchorPoint;
}
2 голосов
/ 04 ноября 2012

Я нуждался в этом пару раз и решил сделать расширение для CCNode, протестировал его abit и, кажется, работает нормально. Может быть действительно полезным для некоторых:)

Он протестирован с 1.x, но и в 2.x тоже должен работать. Поддерживает преобразованные узлы и HD.

Просто добавьте это в свой проект и импортируйте, когда вам это нужно - оно будет добавлено ко всем классам, производным от CCNode. (CCSprite, CCLayer)

Интерфейс

#import "cocos2d.h"

@interface CCNode (Extensions)

// Returns the parent coordinate for an anchorpoint. Useful for aligning nodes with different anchorpoints for instance
-(CGPoint)positionOfAnchorPoint:(CGPoint)anchor;

// As above but using anchorpoint in points rather than percentage
-(CGPoint)positionOfAnchorPointInPoints:(CGPoint)anchor;

//Sets the anchorpoint, to not move the node set lockPosition to `YES`. Setting it to `NO` is equal to setAnchorPoint, I thought this would be good for readability so you always know what you do when you move the anchorpoint
-(void)setAnchorPoint:(CGPoint)a lockPosition:(BOOL)lockPosition;

@end

Осуществление

#import "CCNode+AnchorPos.h"

@implementation CCNode (Extensions)

-(CGPoint)positionOfAnchorPoint:(CGPoint)anchor
{
    float x = anchor.x * self.contentSizeInPixels.width;
    float y = anchor.y * self.contentSizeInPixels.height;

    CGPoint pos = ccp(x,y);

    pos = CGPointApplyAffineTransform(pos, [self nodeToParentTransform]);

    return ccpMult(pos, 1/CC_CONTENT_SCALE_FACTOR());
}

-(CGPoint)positionOfAnchorPointInPoints:(CGPoint)anchor;
{
    CGPoint anchorPointInPercent = ccp(anchor.x/self.contentSize.width, anchor.y/self.contentSize.height);
    return [self positionOfAnchorPoint:anchorPointInPercent];
}

-(void)setAnchorPoint:(CGPoint)a lockPosition:(BOOL)lockPosition
{
    CGPoint tempPos = [self positionOfAnchorPoint:a];
    self.anchorPoint = a;

    if(lockPosition)
    {
        self.position = tempPos;
    }
}

@end
2 голосов
/ 14 апреля 2010

Это хороший вопрос, и я пока не знаю полного ответа.

Как вы могли заметить, anchorPoint нельзя изменить без влияния на масштаб и вращение.

Для масштабированных спрайтов:

Вы должны одновременно изменить точку привязки и положение вашего спрайта. См этот вопрос для подсказки

Для повернутых спрайтов:

Интуиция говорит, что вам нужно будет одновременно изменить anchorPoint, вращение и положение. (Понятия не имею, как это вычислить.)

ПРИМЕЧАНИЕ: Я все еще учусь графическому программированию, поэтому я пока не могу на 100% рассчитать этот материал.

0 голосов
/ 11 апреля 2015

Cocos2d-x + Фиксированная шкала

YourClass.h

virtual cocos2d::Vec2 positionFromSprite(cocos2d::Vec2 newAnchorPoint, cocos2d::Sprite *sprite);

YourClass.m

Vec2 YourClass::positionFromSprite(Vec2 newAnchorPoint, cocos2d::Sprite *sprite) {
    Rect rect = sprite->getSpriteFrame()->getRect();
    Vec2 oldAnchorPoint = sprite->getAnchorPoint();
    float scaleX = sprite->getScaleX();
    float scaleY = sprite->getScaleY();

    Vec2 newPoint = Vec2(rect.size.width * newAnchorPoint.x * scaleX, rect.size.height * newAnchorPoint.y * scaleY);
    Vec2 oldPoint = Vec2(rect.size.width * oldAnchorPoint.x * scaleX, rect.size.height * oldAnchorPoint.y * scaleY);

    Vec2 position = sprite->getPosition();

    position.x -= oldPoint.x;
    position.x += newPoint.x;

    position.y -= oldPoint.y;
    position.y += newPoint.y;

    return position;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...