Spritekit / UIBeziers: Detecting touches / nodeAtPoint - ios

I'm creating my player like this:
UIBezierPath *pPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0)
radius:10
startAngle:0
endAngle:DEGREES_TO_RADIANS(360)
clockwise:YES];
_player = [[SKShapeNode alloc] init];
_player.path = pPath.CGPath;
[_player setFillColor:[UIColor blueColor]];
[_player setStrokeColor:[UIColor clearColor]];
_player.position = arenaCentre;
_player.zPosition = 1;
_player.name = #"player";
I then detect touches on this object using:
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:touchLocation];
The problem is that my shape is too small/ fast to touch sometimes. How could I make the touch zone larger then the visible object?
Is there a best practice for this kind of thing?
Many thanks,
Ian

You could draw a larger shape (or color sprite) of the desired size as the parent of the player shape, and use a fully transparent color.
However this will sometimes find the parent shape, other times the actual shape. So you have to compensate for that.

Related

Creating image which sweeps across the screen

I'm trying to create a banner that sweeps across the current scene. I want to create a banner which sweeps down the screen to show the current round. My attempt at it is creating a UIImageView and add it to the current view. However, i assume its calling the didMoveToView Function and resetting everything in that scene, which is something i dont want it to do. Here is my attempt:
-(void)createBanner{
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Banner"]];
[imageView setFrame:CGRectMake(0,0, imageView.frame.size.width, imageView.frame.size.height)];
[imageView setClipsToBounds:YES];
[self.view addSubview:imageView];
CABasicAnimation *sweep = [CABasicAnimation animationWithKeyPath:#"position"];
sweep.fromValue = [NSValue valueWithCGPoint:CGPointZero];
sweep.toValue = [NSValue valueWithCGPoint:CGPointMake(0.0, self.frame.size.height)];
sweep.duration = 10;
sweep.additive = YES;
[imageView.layer addAnimation:sweep forKey:#"sweep"];
}
EDIT: i am using sprite kit in order to create the game.
As hamobi said, it's best to use an 'SKSpriteNode' in Sprite Kit and not UIKit. Assuming your'e adding to an 'SKScene', your code above translated to Sprite Kit is:
-(void)createBanner{
SKSpriteNode* spriteNode = [SKSpriteNode spriteNodeWithImageNamed:#"Banner"]
//It's good practice not to resize the sprite in code as it should already be the right size but...
spriteNode.size = CGSizeMake(self.size.width, self.size.height)
//Set its center off to the left of the screen for horizontal sweep, or you can do vertical and set it off the top of the screen...
spriteNode.postion = CGPointMake(-spriteNode.size.width/2, self.size.height/2)
self.addChild(spriteNode)
//Then to sweep from left to right...
SKAction* sweep = [SKAction moveTo:CGPointMake(spriteNode.size.width/2, self.size.height/2) duration:10]
spriteNode.runAction(sweep)
}
I think that covers most of it.

How to correctly turn on and off SKEffectNode for a SKNode?

I want to show an effect node if a node is selected. If not, I want to turn off/remove that effect. (I set a node as selected in touchesBegan.)
I use the code below. Turning on and off the effect node is mixing my mind up because I add the main node into an effect node. How should I turn it off without loosing the main node too? I can change the color of the effect to transparent to hide it but it doesn't sound like the right way... Moving main node from effect node to parent of effect node may work but I have to reposition it again so it doesn't sound like the right way too..
What is one of the correct ways of doing this? (correct = good for performance while not increasing coding complexity)
SKShapeNode* tile = [SKShapeNode node];
[tile setPath:CGPathCreateWithRoundedRect(CGRectMake(0, 0, 60, 100), 4, 4, nil)];
tile.strokeColor = tile.fillColor = [UIColor colorWithRed:0.0/255.0
green:128.0/255.0
blue:255.0/255.0
alpha:1.0];
tile.position = CGPointMake(10, 100);
SKEffectNode *effectNode = [[SKEffectNode alloc] init];
GlowFilter *glowFilter = [[GlowFilter alloc] init];
[glowFilter setGlowColor:[[UIColor yellowColor] colorWithAlphaComponent:1]];
[effectNode setShouldRasterize:YES];
[effectNode setFilter:glowFilter];
effectNode.position=CGPointMake(0, 0);
[effectNode addChild:tile];
[self addChild:effectNode];
theEffectNode.shouldEnableEffects = NO;

Stroke a CGPathRef in Objective C

I've looked at similar questions here but I can't make the examples work for me. Since the way I'm creating this path is a bit different than previous examples, I'll state my problem:
I'm trying to visualize a path that sprites are made to follow in a SpriteKit game.
I call this in another method, where I add the shipPath to a SKAction
CGPathRef shipPath = [self buildEnemyShipMovementPath:enemy];
SKAction *followPath = [SKAction followPath:shipPath
asOffset:YES
orientToPath:YES
duration:7];
The path creation method:
- (CGPathRef)buildEnemyShipMovementPath:(SKSpriteNode*)enemy
{
UIBezierPath* bezierPath = [UIBezierPath bezierPath];
// ... path creation code ... //
return bezierPath.CGPath;
}
Given this, what should I do to "see" the path on screen, potentially I'd like to toggle it on and off, for debugging purposes.
SKShapeNode *pathNode = [[SKShapeNode alloc] init];
pathNode.path = [self buildEnemyShipMovementPath:enemy];
pathNode.strokeColor = [SKColor redColor];
pathNode.lineWidth = 0.5f;
pathNode.alpha = 0.4;
pathNode.glowWidth = 5.f;
[self addChild:pathNode]

Make an elastic band type slingshot in spritekit

I'm working on a game where I have a line across the bottom of the screen that I use to launch things up into the air. It should behave like a rubber band or a slingshot. I have hacked together something that works, but it's kind of a bad solution and I'm hoping someone can suggest another way. My way basically involved redrawing a mutablepath by repeated calls to the draw method during the touchesMoved method. Again, I know this is a bad way of doing it, so sorry for the horrible code.
-(void)drawLine:(CGPoint)location
{
[_powerLine removeFromParent];
CGPoint pointTL = CGPointMake(19, 131);
CGPoint pointTR = CGPointMake(308, 131);
CGPoint pointBL = CGPointMake(location.x-10, location.y);
CGPoint pointBR = CGPointMake(location.x+10, location.y);
UIBezierPath *lineShape = [UIBezierPath bezierPath];
[lineShape moveToPoint:pointTL];
[lineShape addLineToPoint:pointBL];
[lineShape addLineToPoint:pointBR];
[lineShape addLineToPoint:pointTR];
_powerLine = [SKShapeNode node];
_powerLine.path = lineShape.CGPath;
_powerLine.lineWidth = 2.0;
_powerLine.strokeColor = [SKColor colorWithRed:0.0 green:0 blue:0 alpha:1];
[self addChild:_powerLine];
CGMutablePathRef powerLinePath = CGPathCreateMutable();
CGPathMoveToPoint(powerLinePath, nil, pointTL.x, pointTL.y);
CGPathAddLineToPoint(powerLinePath, nil, pointBL.x, pointBL.y);
CGPathAddLineToPoint(powerLinePath, nil, pointBR.x, pointBR.y);
CGPathAddLineToPoint(powerLinePath, nil, pointTR.x, pointTR.y);
_powerLine.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:powerLinePath];
_powerLine.physicsBody.categoryBitMask = WFPhysicsCategoryPowerline;
_lastBR = pointBR;
_lastBL = pointBL;
}
I'm hoping there is a better way to do this other than constantly redrawing it when the person pulls the line down to shot the object up in the air. I looked into spring joints but couldn't convince them to work. The other problem I had with spring joints was how to get the image to stretch to match where the line should be. This approach solves trying to stretch an image by simply eliminating the image. It would be nice to use springs so that I could avoid having to hand code the physics of this.
Anyone have thoughts on how to do this?
I'm not sure if you're concerned about how to draw a convincing elastic band onscreen, or how to emulate the physics of one. If it's the former I can't help you much, but if it's the latter you could try something like this! You should be able to copy and paste it into an existing sprite kit app to play around with it, just initialize it and call SKView's presentScene: with it.
(header file)
#import <SpriteKit/SpriteKit.h>
#interface SlingScene : SKScene
#end
(implementation file)
#import "SlingScene.h"
#interface SlingScene ()
#property (nonatomic, strong) SKAction *slingAction;
#end
#implementation SlingScene
- (instancetype)initWithSize:(CGSize)size {
self = [super initWithSize:size];
if (self) {
CGPoint center = CGPointMake(self.size.width/2.0, self.size.height/2.0);
self.slingAction = [SKAction sequence:
#[[SKAction waitForDuration:0.1],
[SKAction runBlock:
^{
[self.physicsWorld removeAllJoints];
}
]]];
// Create a square, which will be slung by the spring
SKSpriteNode *square =
[SKSpriteNode spriteNodeWithColor:[SKColor whiteColor]
size:CGSizeMake(60.0, 60.0)];
square.position = CGPointMake(center.x, center.y - 2*square.size.height);
square.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:square.size];
square.physicsBody.collisionBitMask = 0;
square.name = #"square";
// Create a post to anchor the square to
SKShapeNode *post = [SKShapeNode node];
post.path = CGPathCreateWithEllipseInRect(
CGRectMake(0.0, 0.0, 60.0, 60.0), NULL);
post.fillColor = [SKColor brownColor];
post.strokeColor = [SKColor brownColor];
post.position = CGPointMake(center.x-30.0, center.y-30.0);
post.physicsBody =
[SKPhysicsBody bodyWithCircleOfRadius:60.0 center:center];
// Give the post a near-infinite mass so the square won't tug at it
// and move it around
post.physicsBody.mass = 1000000;
post.physicsBody.affectedByGravity = NO;
// Set their collision bit masks to the same value to allow them to pass
// through each other
post.physicsBody.collisionBitMask = 0;
square.physicsBody.collisionBitMask = 0;
// Add them to the scene
[self addChild:post];
[self addChild:square];
// Connect them via a spring
SKPhysicsJointSpring *spring =
[SKPhysicsJointSpring jointWithBodyA:post.physicsBody
bodyB:square.physicsBody
anchorA:center
anchorB:square.position];
spring.damping = 0.4;
spring.frequency = 1.0;
[self.physicsWorld addJoint:spring];
// Lower gravity from the default {0.0, -9.8} to allow the
// square to be slung farther
self.physicsWorld.gravity = CGVectorMake(0.0, -4.0);
}
return self;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// Move the square to the touch position
SKSpriteNode *square = (SKSpriteNode *)[self childNodeWithName:#"square"];
CGPoint location = [[touches anyObject] locationInNode:self];
[square runAction:[SKAction moveTo:location duration:0.1]];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// Sling the square by
// 1. allowing the spring to accelerate it, and
// 2. removing the spring altogether
[self runAction:self.slingAction];
}
#end
Another method might be to compute the x and y positions relative to a specific point, and apply an impulse in the opposite direction. For example, if you find dx = -100.0 and dy = -100.0, you could use applyImpulse:CGVectorMake(-dx, -dy) to launch it up and right. Using the spring joint gives you some acceleration, however.

dynamic cone shape changes depending on obstacles - reference to Third Eye Crime app

I've seen the Trailer of "Third Eye Crime".
How can you realise the blue field of view cone so that it's shape changes depending on obstacles?
My attempt was to cast rays till an obstacle occurs and then I take the end points of the rays to draw the cone shape.
The problem with my method is that the precision of the cone depends on the number of rays. Besides the more rays are casted the worse the performance.
Here you can see the rays:
Here you can see the cone shape drawn with the end points of the rays:
Are there better solutions?
Your question has been bugging me all day but I can't find a fully working answer. My work notes are too much for me to write it as a comment so I am adding it as an answer.
My first issue was to test for a contact between a field of view line and any obstruction object. Unfortunately SpriteKit only has the contactBitMask which can do this job AND provide contact coordinates.
I looked at SKNode's intersectsNode: but its return value is only a BOOL and we need coordinates.
I also looked at Apple's Sprite Kit Programming Guide's section Searching for Physics Bodies. This deals with line of sight, obstacles, etc... The command used here is bodyAlongRayStart:end:. The return is the first physics body it intersects with but without providing the coordinates for the actual contact point.
The code I ended up with first draws the complete line of sight cone. Next any lines found contacting an object got the contact point using contact.contactPoint and then deleted the offending line. So far so good. But I ran into trouble trying to draw the deleted line to the new end point (contact point). For some inexplicable reason only some of the deleted lines are being redrawn and not all.
Keep in mind this is rough code so slap it, pull it and throw it against the wall a couple of times. You don't really need the array for example. I hope this will steer you in the right direction or you can spot something I am too blind to see.
Side note: I ran this in simulator iPhone (4 inch) landscape.
#import "MyScene.h"
typedef NS_OPTIONS(uint32_t, CNPhysicsCategory)
{
Category1 = 1 << 0,
Category2 = 1 << 1,
Category3 = 1 << 2,
};
#interface MyScene()<SKPhysicsContactDelegate>
#end
#implementation MyScene
{
SKSpriteNode *player;
SKSpriteNode *obstacle1;
SKSpriteNode *obstacle2;
SKSpriteNode *obstacle3;
SKSpriteNode *obstacle4;
NSMutableArray *beamArray;
int beamCounter;
}
-(id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
self.physicsWorld.contactDelegate = self;
beamArray = [[NSMutableArray alloc] init];
beamCounter = 0;
player = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(20, 20)];
player.position = CGPointMake(100, 150);
[self addChild:player];
obstacle1 = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(200, 20)];
obstacle1.name = #"obstacle1";
obstacle1.position = CGPointMake(250, 100);
obstacle1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle1.size];
obstacle1.physicsBody.affectedByGravity = NO;
obstacle1.physicsBody.categoryBitMask = Category2;
obstacle1.physicsBody.collisionBitMask = 0x00000000;
[self addChild:obstacle1];
obstacle2 = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(40, 40)];
obstacle2.name = #"obstacle2";
obstacle2.position = CGPointMake(400, 200);
obstacle2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle2.size];
obstacle2.physicsBody.affectedByGravity = NO;
obstacle2.physicsBody.categoryBitMask = Category2;
obstacle2.physicsBody.collisionBitMask = 0x00000000;
[self addChild:obstacle2];
obstacle3 = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(50, 20)];
obstacle3.name = #"obstacle3";
obstacle3.position = CGPointMake(530, 130);
obstacle3.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle3.size];
obstacle3.physicsBody.affectedByGravity = NO;
obstacle3.physicsBody.categoryBitMask = Category2;
obstacle3.physicsBody.collisionBitMask = 0x00000000;
[self addChild:obstacle3];
for (int y = 0; y <= 320; y++)
{
SKShapeNode *beam1 = [SKShapeNode node];
beam1.name = [NSString stringWithFormat:#"%i",beamCounter++];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, player.position.x, player.position.y);
CGPathAddLineToPoint(pathToDraw, NULL, 600, y);
beam1.path = pathToDraw;
[beam1 setStrokeColor:[UIColor yellowColor]];
[beam1 setLineWidth:2.0];
beam1.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(player.position.x, player.position.y) toPoint:CGPointMake(600, y)];
beam1.physicsBody.affectedByGravity = NO;
beam1.physicsBody.categoryBitMask = Category1;
beam1.physicsBody.contactTestBitMask = Category2;
[self addChild:beam1];
[beamArray addObject:beam1];
}
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//
}
-(void)update:(CFTimeInterval)currentTime
{
//
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
NSLog(#"bodyA:%# bodyB:%#",contact.bodyA.node.name, contact.bodyB.node.name);
uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
if (collision == (Category1 | Category2))
{
CGPoint newEndPoint = contact.contactPoint;
[beamArray removeObject:contact.bodyA.node.name];
[contact.bodyA.node removeFromParent];
SKShapeNode *beam1 = [SKShapeNode node];
beam1.name = [NSString stringWithFormat:#"%i",beamCounter++];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, player.position.x, player.position.y);
CGPathAddLineToPoint(pathToDraw, NULL, newEndPoint.x, newEndPoint.y);
beam1.path = pathToDraw;
[beam1 setStrokeColor:[UIColor greenColor]];
[beam1 setLineWidth:2.0];
[self addChild:beam1];
}
}
#end
Removing the touching lines:
Removing the touching lines and replacing the removed lines:
How I would do it is send out a ray at the edges of view and make note of the points that they hit. Then find points that are important(corners of objects for example), form rays with those points and use those rays to find collisions past those points and finally fill triangles with the points and the "source" of the light.
I might get a chance to make pictures to help demonstrate my algorithm later but this is what I have now.
I think the efficient way to do this is to use Bresenham's Algorithm. There are lots of references and example code in the Wikipedia references section.
http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
Here I've found several answers:
https://code.google.com/p/straightedge/
http://www.redblobgames.com/articles/visibility/

Resources