Search code examples
iossprite-kitskspritenodetouchesbegan

How to change the color of an SKSpriteNode in touchesBegan?


I am new to SpriteKit, and I'm trying to change the color of an SKSpriteNode inside touchesBegan. My attempts failed; can anyone suggest a reason as to why?

This is my code:

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
    /* Setup your scene here */

    self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

   mySKSpriteNode=[SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImage:[UIImage imageNamed:@"bg-1.png"]] size:CGSizeMake(50, 50)];
    [mySKSpriteNode setPosition:CGPointMake(150, 300)];
    mySKSpriteNode.name = @"thisIsMySprite"; // set the name for your sprite
    mySKSpriteNode.userInteractionEnabled = NO;

    [self addChild:mySKSpriteNode];
   }
   return self;
 }
 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {

   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInNode:self];
   SKNode *node = [self nodeAtPoint:location];
   if ([node.name isEqualToString:@"thisIsMySprite"])
   {
      NSLog(@"mySKSpriteNode was touched!");
      [mySKSpriteNode setColor:[UIColor whiteColor]];
   }

 }

The if statement is executed, as "my mySKSpriteNode was touched!" is successfully printed upon touching the node. However, I am not able to change the color of the node. Can someone suggest a method to do so?


Solution

  • I made a mistake, it was not changing colors because I initialized the sprite with a texture as opposed to a color.

    I fixed it with the following code:

     mySKSpriteNode=[SKSpriteNode spriteNodeWithColor:[UIColor redColor]  size:CGSizeMake(50, 50)];