SpriteKit - Stop Clicks on Sprite From Acting Upon Children - ios

I currently use the following to create a button with text using SpriteKit:
SKLabelNode *startButtonText = [SKLabelNode labelNodeWithFontNamed:#"Verdana-Bold"];
startButtonText.text = #"Start";
startButtonText.fontColor = [SKColor colorWithRed:1 green:1 blue:1 alpha:1];
startButtonText.fontSize = 24;
startButtonText.position = CGPointMake(self.size.width/2, self.size.height/2-10);
startButtonText.name=#"startButton";
SKShapeNode *startButton = [[SKShapeNode alloc] init];
startButton.path = [UIBezierPath bezierPathWithRect:CGRectMake(center.x-65.0 , center.y-20.0, 130.0, 40.0)].CGPath;
startButton.fillColor = [SKColor colorWithRed:0.188 green:0.196 blue:0.161 alpha:1];
startButton.strokeColor = nill;
startButtonText.name=#"startButton";
[startButton addChild:startButtonText];
[self addChild:startButton];
My goal is to make it so that when the screen is touched, the touch only registers startButton not start startButtonText via:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
NSLog(#"%#",node.name);
}
In action script, you would simply use:
mouseChildren = false;
Is there anyway this is possible?

Give both buttons a different name. It looks like there's a copy & paste error in your code.
Then check in your touchesBegan which button has been pressed and react on both the same way:
if ([node.name isEqualToString:#"startButton"]||[node.name isEqualToString:#"startButtonText"]) {
...
}

Related

How to remove SCNNode when Tap on it?

I have Creat Cubes using SceneView and i want to disappear cube on which Tap action. How can achieve it?
Here is my code to create Cube
SCNBox *Box = [SCNBox boxWithWidth:2.0 height:2.0 length:2.0
chamferRadius:Radius];
Box.firstMaterial.diffuse.contents = [UIColor whiteColor];
SCNNode *cubeNode = [SCNNode nodeWithGeometry:Box];
[ArrBoxNode addObject:cubeNode];
self.sceneView.backgroundColor = [UIColor redColor];
self.view.backgroundColor = [UIColor grayColor];
cubeNode.position = SCNVector3Make(4,0,0);
[scene.rootNode addChildNode:cubeNode];
self.sceneView.scene = scene;
[self.sceneView sizeToFit];
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.sceneView];
SCNHitTestResult *hitTestResult = [[self.sceneView
hitTest:touchPoint options:nil] firstObject];
SCNNode *hitNode = hitTestResult.node;
for (SCNNode *node in ArrBoxNode) {
[node removeFromParentNode];
}
}
but I'm not able to remove Node from Tap action. Can you please help me, and give better suggestions, thank you... :)
You need remove the node you are touching using [hitNode removeFromParentNode];
Code
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.sceneView];
SCNHitTestResult *hitTestResult = [[self.sceneView hitTest:touchPoint options:nil] firstObject];
SCNNode *hitNode = hitTestResult.node;
[hitNode removeFromParentNode];
}

Spritekit - UITouch effect does not work when SKparticles are taking place over the area

I have a bubble, when touched will pop. This pop effects work fine with the code below. However when a spritekit particle effect is used which covers the bubble, the touch action does not work. When the particle effect finishes, the touch action will work. Does the particle effect have a non-touch field? and is there anyway around this? I attempted to change the z-position but that did not work.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
SKLabelNode *touchedNode = (SKLabelNode *)[self nodeAtPoint:positionInScene];
if ([[touchedNode name] isEqualToString:#"bubbleBall1"]) {
ballNode.position = bubble1.position;
[_gameNode addChild:ballNode];
[bubble1 removeFromParent];
[self playBubblePopSound];
}
}
This is the particle effect im using in the physics contact area.
SKEmitterNode *starCollectParticle = [SKEmitterNode emitterNamed:#"starCollect"];
starCollectParticle.position = star1Node.position;
starCollectParticle.zPosition = 0;
//starCollectParticle.particleLifetime = 2;
[self addChild:starCollectParticle];
It was the z.position. I change the z.position of the particles. This did not work. However also changing the z.position of the SKSpritenode did the trick.
-(void)addBubble1:(CGPoint)pos{
gameObjects = [SKTextureAtlas atlasNamed:#"GameObjects.atlas"];
bubble1 = [SKSpriteNode spriteNodeWithTexture:[gameObjects textureNamed:kBubble]];
bubble1.size = bubble1.texture.size;
bubble1.size = CGSizeMake(70,70);
bubble1.position = pos;
bubble1.name = bubble1CategoryName;
**bubble1.zPosition = 1;**
bubble1.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:bubble1.frame.size.width/2];
bubble1.physicsBody.affectedByGravity = NO;
bubble1.physicsBody.dynamic = NO;
bubble1.physicsBody.usesPreciseCollisionDetection = YES;
bubble1.physicsBody.categoryBitMask = bubble1Category;
bubble1.physicsBody.contactTestBitMask = ballCategory | completeObjectNodeCategory | completeObjectBoxNodeCategory;
bubble1.physicsBody.collisionBitMask = completeObjectNodeCategory | lineNodeCategory;
[_gameNode addChild:bubble1];
}
SKEmitterNode *starCollectParticle = [SKEmitterNode emitterNamed:#"starCollect"];
starCollectParticle.position = star1Node.position;
**starCollectParticle.zPosition = 0;**
//starCollectParticle.particleLifetime = 2;
[self addChild:starCollectParticle];

How to add Highlighted Button in SpriteKit?

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];
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"]];
}
}
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.
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.

Have particle emitter trail follow finger path in spriteKit

I have created a particle emitter in Xcode that has quite a lengthy trail. When i move it inside of the particle generator it leaves a trail following my mouse path.
some background info on my goal:
In my spriteKit game the user drags their finger around the screen to shoot moving objects. I am attempting to create a "Bullet Time" effect where the objects slow down and highlights when the current finger location touches them. When the finger stops moving or they run out of ammo the touchesEnded method is fired shooting all of the highlighted objects. Currently I have the path that they travel showing up as a line drawn to the screen using SKShapeNode & CGPath, but I would like the trail to be highlighted with the emitter trail instead.
In the touches began method I create a circle SpriteNode that moves around wherever the finger moves to (the physics collision is attached to the circle not the path). I've attached the particle trail emitter to this circle and it moves with the circle when I move it around the screen, but does not leave a trail.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
pathToDraw = CGPathCreateMutable();
startPoint = touchLocation;
CGPathMoveToPoint(pathToDraw, NULL, touchLocation.x, touchLocation.y);
lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
lineNode.lineWidth = 2;
lineNode.zPosition = 110;
lineNode.strokeColor = [SKColor whiteColor];
[self addChild:lineNode];
circle = [SKSpriteNode spriteNodeWithTexture:[animationsAtlas textureNamed:#"anim_countdown_9"]];
circle.name = #"circle";
circle.scale = 0.3;
circle.alpha = 0.5;
circle.zPosition = 110;
circle.position = touchLocation;
circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
circle.physicsBody.categoryBitMask = weaponCategory;
circle.physicsBody.dynamic = NO;
circle.physicsBody.contactTestBitMask = billyCategory;
circle.physicsBody.collisionBitMask = 0;
[self addChild:circle];
pathEmitter = [SKEmitterNode skt_emitterNamed:#"FollowPath"];
//pathEmitter.position = circle.position;
//pathEmitter.targetNode = self;
//pathEmitter.scale = 0.2;
//pathEmitter.zPosition = 60;
[circle addChild:pathEmitter];
}
In touchesMoved method I move the circle accordingly to the new position
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInNode:self];
circle.position = currentPoint;
SKAction *wtf = [SKAction followPath:pathToDraw asOffset:NO orientToPath:YES duration:0.1];
//pathEmitter.position = currentPoint;
//[pathEmitter runAction:wtf];
//pathEmitter.particleAction = wtf;
pathEmitter.particleAction = [SKAction moveTo:currentPoint duration:1.0];
CGPathAddLineToPoint(pathToDraw, NULL, currentPoint.x, currentPoint.y);
lineNode.path = pathToDraw;
I've tried setting pathEmitter.targetNode = self; like this post Making a particle follow a path in spriteKit suggests but then the emitter doesn't appear at all.
and if i set the particleAction to followPath it does not leave a trail either.
In my code you can see I've commented out some lines, basically I've tried every combination of targetNode & particleAction I can think of.
Any suggestions on how I can get the emitter to leave a trail on my finger path?
thanks
actually pathEmitter.targetNode = self; is the one that will let you have a particle to leave a trail as your object moves, I'm not seeing any reason why it's not working for you 'cause I've been using this method for like a long time ago now, check your position specially for method touchesMoved
I think this code is all what you need;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
circle = [SKSpriteNode spriteNodeWithTexture:[animationsAtlas textureNamed:#"anim_countdown_9"]];
circle.name = #"circle";
circle.scale = 0.3;
circle.alpha = 0.5;
circle.zPosition = 110;
circle.position = touchLocation;
circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
circle.physicsBody.categoryBitMask = weaponCategory;
circle.physicsBody.dynamic = NO;
circle.physicsBody.contactTestBitMask = billyCategory;
circle.physicsBody.collisionBitMask = 0;
[self addChild:circle];
pathEmitter = [NSKeyedUnarchiver unarchiveObjectWithFile: [[NSBundle mainBundle] pathForResource:#"FollowPath"ofType:#"sks"]];
pathEmitter.position = CGPointMake(0, -60);
[circle addChild:pathEmitter];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInNode:self];
circle.position = currentPoint;
}
- (void)update:(CFTimeInterval)delta
{
if (!pathEmitter.targetNode) {
pathEmitter.targetNode = self;
}
}

Sprite Kit Joints

I am trying to make an animated character that can reach out for things on the screen, without moving his torso.
If he can not reach than his hand should go the maximal amount in this direction and then be counteracted by the physical limitation of his static torso.
So in my code the green rectangle (hand) moves where I click and the torso follows.
I would like to be able to make the red rect (body) stationary and make the green rectangle "point" at the touch point position.
I have tried to apply a fixed joint to between the scene and the red body rectangle, but this did not seem to work.
- (void) createSceneContent
{
SKSpriteNode *body = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(100, 100)];
body.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:body];
body.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:body.size];
body.physicsBody.affectedByGravity = NO;
body.physicsBody.dynamic = YES;
self.hand = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(150, 20)];
self.hand.position = CGPointMake(body.position.x + body.size.width / 2 + self.hand.size.width / 2, body.position.y);
[self addChild:self.hand];
self.hand.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.hand.size];
self.hand.physicsBody.dynamic = NO;
self.scene.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
[self.physicsWorld addJoint:[SKPhysicsJointPin jointWithBodyA:body.physicsBody bodyB:self.hand.physicsBody anchor:CGPointMake(body.position.x + body.size.width / 2, body.position.y)]];
[self.hand runAction:[SKAction moveByX:100 y:10 duration:0.1]];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
[self.hand runAction:[SKAction moveTo:location duration:0.1]];
}
First of all, you don't really need to use physics here, if you only want the arm to point at the touched location.
Just change the arm node's anchorPoint to the shoulder (where you would put the pin on the joint) and rotate it around that point (the point is held in a helper shoulderNode, so that it's easy to convert to its coordinates later). You can calculate the rotation angle using atan2f. Here's the code:
- (void) createSceneContent
{
SKSpriteNode *body = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(100, 100)];
body.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:body];
self.hand = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(150, 20)];
self.hand.position = CGPointMake(body.position.x + body.size.width*0.5, body.position.y);
self.hand.anchorPoint = CGPointMake(0, 0.5);
[self addChild:self.hand];
SKNode *shoulderNode = [SKNode node];
shoulderNode.position = self.hand.position;
shoulderNode.name = #"shoulderNode";
[self addChild:shoulderNode];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
CGPoint locationConv = [self convertPoint:location toNode:[self childNodeWithName:#"shoulderNode"]];
self.hand.zRotation = (atan2f(locationConv.y, locationConv.x));
}
On the other hand, if you ever need to use physics bodies here, it's probably a bad idea to use SKActions to move the arm, and you also might want to set body.physicsBody.dynamic = NO to make the torso static. Then, make sure you add the pin joint correctly, and set its frictionTorque property to a high value to get less dangling. One of the ways to make the hand point at the right location is its velocity vector set in the update method - just use the converted location coordinates (here they are relative to the body node's centre). Full example code:
- (void) createSceneContent {
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
body = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(100, 100)];
body.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:body];
body.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:body.size];
body.physicsBody.dynamic = NO;
body.physicsBody.affectedByGravity = YES;
self.hand = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(20, 150)];
// experiment with the anchorPoint for different results
self.hand.anchorPoint = CGPointMake(0.5, 0);
self.hand.position = CGPointMake(body.position.x, body.position.y);
[self addChild:self.hand];
self.hand.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:self.hand.size];
self.hand.physicsBody.dynamic = YES;
self.hand.physicsBody.affectedByGravity = NO;
SKPhysicsJointPin *pinHand = [SKPhysicsJointPin jointWithBodyA:body.physicsBody bodyB:self.hand.physicsBody anchor:CGPointMake(body.position.x, body.position.y-5)];
[self.physicsWorld addJoint:pinHand];
// experiment with the friction torque value to achieve desired results
pinHand.frictionTorque = 1.0;
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
location = [touch locationInNode:self];
}
-(void)update:(CFTimeInterval)currentTime {
CGPoint locationConv = [self convertPoint:location toNode:body];
// experiment with the multiplier (here: 10) for faster/slower movement
self.hand.physicsBody.velocity = CGVectorMake(locationConv.x*10, locationConv.y*10);
}
Hope that helps!

Resources