2

I know how to add Button in SpriteKit.

I have done with SKSpriteNode. However i don't know how to add highlight button like UIButton.

I mean when i pressing SKSpriteNode(Button), i want to show highlighted image like UIButton from UIKit.

How can i do that?

Here is my codes that for Button with SKSpriteNode.

self.playButton = [SKSpriteNode spriteNodeWithImageNamed:@"playButton.png"];
self.playButton.position = CGPointMake(self.frame.origin.x + 400, 100);
self.playButton.name = @"playButton";
self.playButton.zPosition = 2;
[self addChild:self.playButton];
Fire Fist
  • 7,032
  • 12
  • 63
  • 109

3 Answers3

3

I Tried and got what you are exactly looking for,

  BOOL isMySpriteNodeTouched = NO;
 mySprite = [[SKSpriteNode alloc]initWithImageNamed:@"ball"];
 mySprite.position = CGPointMake(self.size.width/2.0f, self.size.height/2.0f);
 mySprite.name = @"mySprite";
[self addChild:mySprite];


 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    for (UITouch *touch in touches)
      {
           CGPoint touchPoint = [touch locationInNode:self];
           SKNode *localNode = [[SKNode alloc]init];
           localNode = [self nodeAtPoint:touchPoint];

           if ([localNode.name isEqualToString:mySprite.name])
          {
               mySprite.texture = [SKTexture textureWithImage:[UIImage imageNamed:@"highlightedBall"]];
             isMySpriteNodeTouched = YES;
          }
 }



-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
   {
     if(isMySpriteNodeTouched)
       {
         isMySpriteNodeTouched = !isMySpriteNodeTouched;
         mysprite.texture = [SKTexture textureWithImage:[UIImage imageNamed:@"ball"]];
        } 
   }
Jaffer Sheriff
  • 1,444
  • 13
  • 33
2

One solution is to create two SKSpriteNodes, one for the active state and one for the default state, and add both of them to your view.

In your touchesMoved and touchesEnded methods, hide and unhide the active and default buttons accordingly.

Here's a tutorial in Swift.

Sudeep
  • 796
  • 6
  • 16
1

You can create a UIButton in SK using the view property in the method -(void)didMoveToView:(SKView *)view.

All the UIButton features, including highlight will be accessible.

sangony
  • 11,636
  • 4
  • 39
  • 55