SKShapeNode Detect Two Lines Intersection - ios

I am working on a application and i am drawing line based on user touch of user finger. Once the touch end event received the line is converted to last path. A new line is draw with name "Current path" node when a new touch began event received. I added a physics body for both the line with opposite contact bit mask but i am not able to receive collision event.
Following is my code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
currentPath = CGPathCreateMutable();
currentPathNode = [self newLineNodeWithFillColor : CURRENT_LINE_COLOR];
CGPathMoveToPoint(currentPath, NULL, positionInScene.x, positionInScene.y);
currentPathNode.path = currentPath;
[self addChild:currentPathNode];
uint32_t contactBitMask = circleCategory | lastPathCategory;
[self addPhysicsBodyForLine:currentPathNode withCategoryBitMask:drawPathCategory withContactBitMask:contactBitMask];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(currentPath, NULL, positionInScene.x, positionInScene.y);
currentPathNode.path = currentPath;
uint32_t contactBitMask = lastPathCategory;
[self addPhysicsBodyForLine:currentPathNode withCategoryBitMask:drawPathCategory withContactBitMask:contactBitMask];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if(lastPath == nil){
lastPath = CGPathCreateMutable();
}
CGPathAddPath(lastPath, nil, currentPath);
[lastPathNode removeFromParent];
if(currentPathNode != nil){
[currentPathNode removeFromParent];
currentPathNode = nil;
}
lastPathNode = [self newLineNodeWithFillColor : LAST_LINE_COLOR];
lastPathNode.path = lastPath;
[self addChild:lastPathNode];
[self addPhysicsBodyForLine:lastPathNode withCategoryBitMask:lastPathCategory withContactBitMask:drawPathCategory];
CGPathRelease(currentPath);
}
- (void) addPhysicsBodyForLine:(SKShapeNode*)node withCategoryBitMask:(uint32_t)category withContactBitMask:(uint32_t)contactBitMask{
node.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:node.path];
node.physicsBody.categoryBitMask = category;
node.physicsBody.contactTestBitMask = contactBitMask;
node.physicsBody.collisionBitMask = contactBitMask;
node.physicsBody.dynamic = YES;
node.physicsBody.usesPreciseCollisionDetection = YES;
}
But collision is not Detected? Any Solution.

Collisions do not work that way. You will only register a collision if you use physics to move a node's position. Creating a new physics body over (or across) an already existing physics body will not register a collision.
You can use -(BOOL)intersectsNode:(SKNode *)node every time a new path is drawn to check if the new node intersects any other node.

Related

Adding a physics body to a drawn line

I am working on an iOS app with sprite kit where I draw a line in the following way:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
lineNode.strokeColor = [SKColor blackColor];
lineNode.lineWidth = 5.0f;
[self addChild:lineNode];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode.path = pathToDraw;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPathRelease(pathToDraw);
}
This is working exactly how I want it to, but I am not sure where to begin with my next step.
I want to create a physics body for the line that I have just drawn.
I would preferable to this in the touchesEnded method.
How can I add a physics body to the line regardless of its width?
My best guess is to track all the points, then do some math to figure out a path along the edge of the line, then add the physics body.
Is there a better way to do this before I dive into my approach?

SKPhysicsBody from a line (not closed polygon)

I am trying to create an SKPhysicsBody from a line drawn in the scene. This line is not a closed polygon, but simply created while tracking the users finger in touchesMoved. I need to create a physics body out of this line so that a ball bounces off of it as if it were a ledge, but I can't seem to figure out how to do that.
The closest thing I've found is bodyWithPolygonFromPath, but it only works when the line has been closed into a polygon.
I'm very new to iOS programming (this is my first project) so please take it easy!
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[lineNode removeFromParent];
CGPathRelease(pathToDraw);
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
lineNode.strokeColor = [SKColor redColor];
[self addChild:lineNode];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode.path = pathToDraw;
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
lineNode.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:lineNode.path];
lineNode.physicsBody.categoryBitMask = paddleCategory;
lineNode.physicsBody.collisionBitMask = ballCategory | paddleCategory;
lineNode.physicsBody.contactTestBitMask = ballCategory | paddleCategory;
}
Does the line need to move or react to collisions, or just cause collisions?
If the former, you need a dynamic body — and a dynamic body has to have volume (well, area) so an open path won't work. In this case you could either loop the path back along itself to close it (probably easy to code but hard to make work right) or approximate the path with a collection of narrow rectangular bodies.
If the latter, a static body will do. You can create one from a line segment between two points with bodyWithEdgeFromPoint:toPoint:, or from a series of segments with bodyWithEdgeChainFromPath:.

Drawing line with Touch iOS Sprite Kit

Im using the following code to draw lines in my sprite kit scene but nothing shows up. But the node counts goes up. Can anyone see what could be the problem. Ive been fighting with this code forever
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
lineNode.strokeColor = [SKColor redColor];
//lineNode.lineWidth = 2;
[self addChild:lineNode];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode.path = pathToDraw;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
// lineNode.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:pathToDraw];
// lineNode.physicsBody.dynamic = NO;
// lineNode.physicsBody.categoryBitMask = lines;
// lineNode.physicsBody.contactTestBitMask = 0;
// lineNode.physicsBody.collisionBitMask = blueParticles | redParticles| yellowParticles;
CGPathRelease(pathToDraw);
}
Edit------ Code works when background node removed..How can I set up my background node so that I can daw overtop? Thanks
SKSpriteNode *background;
if(screenHeight == 480){
background = [SKSpriteNode spriteNodeWithImageNamed:#"iPhone4BG.png"];
}
if(screenHeight == 568){
background = [SKSpriteNode spriteNodeWithImageNamed:#"iPhone5BG.png"];
}
if(screenHeight == 667){
background = [SKSpriteNode spriteNodeWithImageNamed:#"iPhone6BG.png"];
}
if(screenHeight == 736){
background = [SKSpriteNode spriteNodeWithImageNamed:#"iPhone6PlusBG.png"];
}
background.position = CGPointMake(screenWidth/2, screenHeight/2);
background.size = CGSizeMake(screenWidth, screenHeight);
// [self addChild:background];
NOTE Core issue was Simulator not rendering a path that isn't closed. On the device the issue doesn't exist. Also a background element was involved that the original poster didn't mention and wasn't represented in code. This answer will solve the issue on the simulator.
To fix your problem, modify your code as follows :
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
// add this line to fix your issue
CGPathMoveToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode.path = pathToDraw;
}
The core issue is that when it goes to render the path, it doesn't have a complete path. Your current approach is to be constantly modifying the path on each touchMove.
The way you close a sub path is :
CGPathCloseSubpath(pathToDraw);
However I chose to just use CGPathMoveToPoint each time you added a segment to the path.
From CGPath reference for CGPathMoveToPoint :
This function ends the subpath already in progress (if any) and starts a new subpath, initializing the starting point and the current point to the specified location (x,y) after an optional transformation.
I am closing the current subpath before it gets rendered, and also setting the start location for the next segment.
However, you are going to run into major issues with performance as defined in the link in the the comments if you are going to be drawing a long line or many lines. Draw a really long line, and you will see what I mean. With minimal line drawing, you might get away with the current approach.
Sadly, drawing of this nature with SKShapeNode is not as optimized as it should be.
I think this is what you are trying to implement. It draws a temporary line (white) as you move your finger and draws a final line (red) when you lift your finger. You will need to declare a CGPoint instance variable named startingPoint and delete the CGMutablePathRef ivar named pathToDraw. The code can be modified to draw multiple, connected line segments as well.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
startingPoint = positionInScene;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
// Remove temporary line if it exist
[lineNode removeFromParent];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, startingPoint.x, startingPoint.y);
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
//CGPathRelease(pathToDraw);
lineNode.strokeColor = [SKColor whiteColor];
lineNode.lineWidth = 1;
[self addChild:lineNode];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
// Remove temporary line
[lineNode removeFromParent];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, startingPoint.x, startingPoint.y);
CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
SKShapeNode *finalLineNode = [SKShapeNode node];
finalLineNode.path = pathToDraw;
//CGPathRelease(pathToDraw);
finalLineNode.strokeColor = [SKColor redColor];
finalLineNode.lineWidth = 1;
[self addChild:finalLineNode];
}

touchesMoved on a specific moving object

Im using Spritekit to create a game for iOS 7. The game has circles moving across the screen using this code
_enemy = [SKSpriteNode spriteNodeWithImageNamed:#"greeny"];
_enemy.position = CGPointMake(CGRectGetMidX(self.frame)+300,
CGRectGetMidY(self.frame));
_enemy.size = CGSizeMake(70, 70);
_enemy.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:35];
_enemy.physicsBody.mass = 0;
_enemy.physicsBody.categoryBitMask = Collisiongreen;
[_enemies addObject:_enemy];
NSLog(#"Enemies%lu",(unsigned long)_enemies.count);
[self addChild:_enemy];
[_enemy runAction:[SKAction moveByX:-900 y:0 duration:4]];
[self runAction:[SKAction playSoundFileNamed:#"Spawn.wav" waitForCompletion:NO]];
[self runAction:[SKAction sequence:#[
[SKAction waitForDuration:1.4],
[SKAction performSelector:#selector(move)
onTarget:self],
]]];
I would like to have it that when the user touches one of the objects moving across the screen that they can move it with their finger either up or down (thats why I'm using touches moved)
The code i have set up right now is
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if(_dead)
return;
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if(CGRectContainsPoint(_enemy.frame, location)){
[_enemy runAction:[SKAction moveTo:[[touches anyObject] locationInNode:self] duration:0.01]];
}
My problem is that if i touch it the object will move a few pixels but will stop right after. How can I get it to move with my finger and if i let go it will continue moving left like programed before? Thanks!!
So the trick here is that in the touchesMoved method, you want the enemy's postion set to the location of your touch. Use the touchesEnded method to execute a method that makes the enemy continue in the direction of your last touch. This is a rough non-tested example.
You need to store the difference of the current location with the previous location.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if(_dead)
return;
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if(CGRectContainsPoint(_enemy.frame, location)){
someBool = False;
[_enemy setPosition:location];
changeInX = location.x - lastX;
changeInY = location.y - lastY;
lastX = location.x;
lastY = location.y;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
someBool = True;
}
- (void)update:(NSTimeInterval)currentTime
{
...
if (someBool) {
enemy.position = CGPointMake((enemy.position.x + changeInX), (enemy.position.y + changeInY));
}
...
}

Passing iOS sprites from one class to another

I have a Spritekit project in xcode on my main screen. However I would really like to manage it from another class so as to not cluster my main. So I added a new class to manage and handle it. Sadly I can't seem to get it to show in my main (or I might be doing it wrong). My myscene.m consists of pretty much the same code including the spaceship and this is where I moved the code too ( I didn't bother adding the methods like touchesBegan)
// joysitck.m
// controlpad
//
#import "joysitck.h"
#implementation joysitck
{
BOOL controlButtonOn;
}
float controlx=200;
float controly=200;
float touchX = 0.0;
float touchY=0.0;
- (instancetype)init
{
if (self = [super init]) {
self.name = #"controlPadNode";
SKSpriteNode *controlPadNode = [SKSpriteNode spriteNodeWithImageNamed:#"game-controller-frontb"];
controlPadNode.position = CGPointMake(controlx,controly);
[controlPadNode setScale:0.5];
controlPadNode.name = #"controlPadNode";
controlPadNode.zPosition = 1.0;
[self addChild:controlPadNode];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//if control pad touched
if ([node.name isEqualToString:#"controlPadNode"]) {
touchX = location.x;
touchY = location.y;
controlButtonOn= true;
}
}
//when touch moves
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//if control pad touched
if ([node.name isEqualToString:#"controlPadNode"]) {
touchX = location.x;
touchY = location.y;
controlButtonOn= true;
}
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
//if control pad touched
if ([node.name isEqualToString:#"controlPadNode"]) {
controlButtonOn= false;
}
}
//update method
-(void)update:(NSTimeInterval)currentTime {
if (controlButtonOn) {
//the control pad
SKNode *controlNode = [self childNodeWithName:#"controlPadNode"];
SKNode *node = [self childNodeWithName:#"spaceShipNode"];
float angle = atan2f (touchY - controly, touchX - controlx) ;
SKAction *moveShip=[SKAction moveByX:6*cosf(angle) y:0 duration:0.005];
[node runAction: moveShip];
}
}
#end
You haven't added joystick node to the scene.
Add this code to MyScene's initWithSize method (before [self addship]):
joysitck *joysitckNode = [[joysitck alloc] init];
[self addChild:joysitckNode];

Resources