Sprite Kit Joints - ios

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!

Related

Can't seem to figure what's wrong here

I've used this same exact code before, and it worked perfect every time. However, I'm trying to use it to move the paddle sprite along a horizontal path at position 100 for y and it updates with the location of my touch but for some reason it's not moving at all. I can't spot what's wrong. Can someone take a look and let me know?
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
for (UITouch *touch in touches){
CGPoint location = [touch locationInNode:self];
CGPoint newPosition = CGPointMake(location.x, 100);
//stop the paddle from going too far
if (newPosition.x < self.paddle.size.width/ 2) {
newPosition.x = self.paddle.size.width/ 2;
}
if (newPosition.x > self.size.width - (self.paddle.size.width/ 2)) {
newPosition.x = self.size.width - (self.paddle.size.width/ 2);
}
self.paddle.position = newPosition;
}
}
-(void) addPlayer:(CGSize)size {
SKSpriteNode *paddle = [SKSpriteNode spriteNodeWithImageNamed:#"paddle"];
//resize sprite
paddle.size = CGSizeMake(125, 31.25);
//position sprite
paddle.position = CGPointMake(size.width/2, 100);
//add physics body to paddle
paddle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:paddle.frame.size];
//change to static so wont be moved by physics
paddle.physicsBody.dynamic = NO;
//add sprite to scene
[self addChild:paddle];
}
-(instancetype)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]){
self.backgroundColor = [SKColor colorWithRed:(29.0f/255) green:(29.0f/255) blue:(29.0f/255) alpha:1.0];
//change gravity
self.physicsWorld.gravity = CGVectorMake(0, 0);
//add physics body to scene
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
[self addPlayer:size];
[self addBricks:size];
[self addBall:size];
}
return self;
}

SpriteKit - Stop Clicks on Sprite From Acting Upon Children

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

Getting location of section of sprite

I'm using IOS7's sprite kit and using NSSpriteNode with default anchor of (.5, .5) [center]. The sprite will be rotating around a lot, is there a way to get the location relative to the anchor point? Like, if I'm looking for the sprites top-center anchorpoint of (.5,1) or bottom-center (.5, 0)? This way I can always get the same location of a part of a sprite however it is rotated?
self.player = [SKSpriteNode spriteNodeWithImageNamed:#"ship.png"];
self.player.anchorPoint = CGPointMake(.5, 1);
CGPoint p = [self.player convertPoint:self.player.position toNode:self]];
NSLog(#"x=%f,y=%f", p.x, p.y);
self.player.anchorPoint = CGPointMake(.5, 0);
CGPoint p = [self.player convertPoint:self.player.position toNode:self]];
NSLog(#"x=%f,y=%f", p.x, p.y);
This ends up yielding the same point even though I'm changing my anchor point to be different parts. I know this is a bad idea to change the anchor point, but trying to give an idea of what I'm trying to do.
I'd like a method something like:
CGPoint imageTopLoc = [self.player getLocationUsingAnchorPoint:CGPointMake(.5, 1)];
CGPoint imageBottomLoc = [self.player getLocationUsingAnchorPoint:CGPointMake(.5, 0)];
// calculate vector of direction between of two points... (next)
Thanks,
Chris
This code returns the coordinates / touch point inside a node, regardless of the node's rotation. (It's based upon the SpriteKit Game template.)
Is that what you are looking for?
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
SKSpriteNode *ship = [SKSpriteNode spriteNodeWithImageNamed:#"Spaceship"];
ship.name = #"ship";
ship.position = CGPointMake(100, 100);
ship.zRotation = M_PI * 0.5;
[self addChild:ship];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKNode *ship = [self childNodeWithName:#"ship"];
CGPoint p = [self convertPoint:location toNode:ship];
NSLog(#"x=%f,y=%f", p.x, p.y);
}
}

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;
}
}

How to calibrate a sprites touchLocation after zoom

I add a sprite on the background sprite and then zoom (pinch) the background and by that the sprite as well.
After the zoom i want to be able to click right on the "zoomed" sprite and then move (pan) it. However, to catch the sprite i have to click outside of the sprite. I guess that is due to the zoom and coordinates.
I would really need some help how to make it so that i always only need to click on the actual sprite if it is in it's original state or zoomed up or down.
I will also implement UIScrollView so i can move around the background but would like to fix this first.
Here is the code i use to test this:
- (void)didMoveToView:(SKView *)view {
_background = [SKSpriteNode spriteNodeWithImageNamed:#"background"];
_background.name = #"background";
[_background setAnchorPoint:CGPointZero];
// _background.anchorPoint = CGPointMake(0.0, 0.1);
self.scaleMode = SKSceneScaleModeResizeFill;
[self addChild:_background];
SKLabelNode *texT = [SKLabelNode labelNodeWithFontNamed:#"Ariel"];
texT.text = #"X";
texT.position = CGPointMake(160, 260);
[_background addChild:texT];
_panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(handlePan:)];
[self.view addGestureRecognizer:_panGesture];
_pinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(handlePinch:)];
[self.view addGestureRecognizer:_pinchGesture];
/* Setup your scene here */
self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:#"Spaceship"];
sprite.xScale = 0.2;
sprite.yScale = 0.2;
sprite.position = CGPointMake(160, 260);
sprite.name = #"sprite";
[_background addChild:sprite];
}
- (void)handlePan:(UIPanGestureRecognizer *)sender {
NSLog(#"handlePan:");
if (![_currentNode.name isEqualToString:#"background"]) {
_touchLocation = [sender locationInView:sender.view];
_touchLocation = [self convertPointFromView:_touchLocation];
_currentNode.position = _touchLocation;
}
}
- (void)handlePinch:(UIPinchGestureRecognizer *) sender {
NSLog(#"handlePinch: %f",sender.scale);
[self runAction:[SKAction scaleBy:sender.scale duration:0]];
sender.scale = 1;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"touchesBegan");
//////DO THE FIRST TOUCH//////
_actualTouch = [touches anyObject];
_touchLocation = [_actualTouch locationInNode:self];
_currentNode = [self nodeAtPoint:_touchLocation];
NSLog(#"TouchBegan:_touchLocation:%#", NSStringFromCGPoint(_touchLocation));
NSLog(#"_currentNode.name: %#", _currentNode.name);
}
#end
I had this same problem and I found that the solution is to resize instead of scale. The physics seem to still work as expected and now the touch events will too. I came across this solution here. The scaleMode in your didMoveToView needs to be changed as well, see below.
self.scaleMode = SKSceneScaleModeAspectFill;
- (void)handlePinch:(UIPinchGestureRecognizer *) sender {
NSLog(#"handlePinch: %f",sender.scale);
//[self runAction:[SKAction scaleBy:sender.scale duration:0]];
self.size = CGSizeMake(self.size.width/sender.scale,self.size.height/sender.scale);
sender.scale = 1;
}
In my own implementation I had set upper and lower limits to the zoom level as well.

Resources