如何获得UIColor / SKColor的名称(即[UIColor redColor] - > @" red"

时间:2014-05-02 18:30:43

标签: objective-c colors sprite-kit

我有点问标题中的问题,但假设我有一个UIColor(即[UIColor redColor]。我如何让NSString等于@" red"或者我怎么能找到一个颜色是否与[UIColor redColor]相同?

例如我尝试过,

SKSpriteNode *player = [SKSpriteNode spriteNodeWithImageNamed:@"image"];
[player runAction:[SKAction colorWithColor:[SKColor blueColor] withColorBlendFactor:1 duration:0.01];
[self addChild:player];

然后:

if (player.color == [SKColor blueColor]) { //Also I have tried 'isEqual' and that didn't work either!
}

请帮助我!提前谢谢!

1 个答案:

答案 0 :(得分:1)

我假设您不知道rmaddy已经建议过的userData,所以我会给你一些示例代码。首先,这就是Apple所说的userData:

  

您可以使用此属性将自己的数据存储在节点中。例如,您可以存储有关每个节点的游戏特定数据,以便在游戏逻辑中使用。这可以是创建自己的节点子类来保存游戏数据的有用替代方法。   Sprite Kit不会对存储在节点中的数据执行任何操作。但是,在归档节点时会归档数据。

@implementation MyScene
{
     SKSpriteNode *frank;
     SKSpriteNode *sally;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
         frank = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(50, 50)];
         frank.position = CGPointMake(100, 100);
         frank.userData = [NSMutableDictionary dictionary];
         [frank.userData setValue:@"blue" forKey:@"color"];
         [self addChild:frank];

         sally = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
         sally.position = CGPointMake(200, 100);
         sally.userData = [NSMutableDictionary dictionary];
         [sally.userData setValue:@"red" forKey:@"color"];
         [self addChild:sally];
     }
     return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     UITouch *touch = [touches anyObject];
     CGPoint location = [touch locationInNode: self];
     SKNode *node = [self nodeAtPoint:location];

     NSMutableDictionary *tempDictionary = node.userData;
     NSString *tempString = [NSString stringWithFormat:@"%@",[tempDictionary objectForKey:@"color"]];

    if([tempString isEqualToString:@"blue"])
        NSLog(@"My color is blue");

    if([tempString isEqualToString:@"red"])
        NSLog(@"My color is red");
}