Changing the image of a SKSprite to an SKShapeNode

2019-02-28 20:33发布

Sprite Kit, Xcode.

I need to find a way to change a sprites image within the program itself. I know how to create jpg files and make them into the sprite image...

But for this program, I need to draw circles/polygons (which may change inside the program) using SKShapeNode, and then transferring this to the SKSpriteNode's image.

Let's say I have declared:

SKSpriteNode *sprite;
SKShapeNode *image;

How would I do this with these variables?

Thanks!

EDIT: I mean texture when I say image.

2条回答
时光不老,我们不散
2楼-- · 2019-02-28 20:48

If I understand your question correctly, you can achieve what you're after using the textureFromNode method on SKView.

In your SKScene:

-(void)didMoveToView:(SKView *)view {
    SKShapeNode *shape = [SKShapeNode shapeNodeWithCircleOfRadius:100];
    shape.fillColor = [UIColor blueColor];
    shape.position  = CGPointMake(self.size.width * 0.25, self.size.height * 0.5);
    [self addChild:shape];

    SKTexture *shapeTexture = [view textureFromNode:shape];
    SKSpriteNode* sprite = [SKSpriteNode spriteNodeWithTexture: shapeTexture];
    sprite.position = CGPointMake(self.size.width * 0.75, self.size.height * 0.5);
    [self addChild:sprite];
}

Hope that helps!

查看更多
孤傲高冷的网名
3楼-- · 2019-02-28 21:04

You cannot change a SKSpriteNode image once you assign it. To do what you want, you need to create a SKSpriteNode using a texture.

- (instancetype)initWithTexture:(SKTexture *)texture

To change a SKSpriteNode's texture you assign a new texture using its texture property. You can also do this using an image converted to a texture like this:

myNode.texture = [SKTexture textureWithImageNamed:@"imageName"];

As for a SKShapeNode, you cannot assign an image. Only a path, rect, circle, ellipse or points. Look at the SKShapeNode class docs section Creating a Shape Path for more info.

查看更多
登录 后发表回答