SKSpritenode not responding in TouchesBegan - xcode

In my game, when player contact with a flag (using DidBeginContact) I add an SKSpritenode "nextlevel" (which is not responding in TouchesBegan and I don't know why. The NSLog code in TouchesBegan is not working.
This my code:
-(void)nextlevel
{
nextlevel = [SKSpriteNode spriteNodeWithImageNamed:#"nextlevel.png"];
nextlevel.userInteractionEnabled = NO;
nextlevel.name = #"nextlevel";
nextlevel.position = CGPointMake(self.size.width / 2.0, self.size.height / 2.0);
[self addChild:nextlevel];
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if((firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == flagCategory) ||
(firstBody.categoryBitMask == flagCategory && secondBody.categoryBitMask == playerCategory))
{
// PLAYER WINS
NSLog(#"player touches flag");
SKAction * wait = [SKAction waitForDuration:1.2];
SKAction *performSelector = [SKAction performSelector:#selector(nextlevel) onTarget:self];
[self runAction:[SKAction sequence:#[wait, performSelector]]];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
// Nextlevel splash screen
if ([node.name isEqualToString:#"nextlevel"]) {
NSLog(#“Next Level was touched!");
}
}

It's possible your SKSpriteNode is obstructed by another Node on top of it.
Try setting the zPosition above all other nodes. Try different values depending on the zPositions of the other nodes in your scene.
nextlevel.zPosition = 10.0f;

Related

SpriteKit physicsBody for a line

I am developing a game with SpriteKit. In my game, the player should be able to draw a line and have things interact with it. I'm using a simple SKShapeNode drawn with a CGMutablePathRef. However when I add the physicsBody to the line, it automatically reconnects the end of the line to the start. The result is if the user draws a curve, the physicsBody is the shape of a semicircle.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKShapeNode *line = [SKShapeNode node];
CGMutablePathRef pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, location.x, location.y);
line.path = pathToDraw;
[line setStrokeColor:[UIColor redColor]];
[line setLineWidth:5];
[line setLineCap:kCGLineCapRound];
[line setLineJoin:kCGLineJoinRound];
line.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:pathToDraw];
line.physicsBody.dynamic = NO;
line.physicsBody.restitution = 1;
line.name = #"line";
[self addChild:line];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
SKShapeNode *oldLine = (SKShapeNode *)[self childNodeWithName:#"line"];
CGMutablePathRef pathToDraw = (CGMutablePathRef)oldLine.path;
CGPathAddLineToPoint(pathToDraw, NULL, location.x, location.y);
[self enumerateChildNodesWithName:#"line" usingBlock:^(SKNode *node, BOOL *stop) {
[node removeFromParent];
}];
SKShapeNode *line = [SKShapeNode node];
line.path = pathToDraw;
[line setStrokeColor:[UIColor redColor]];
[line setLineWidth:5];
[line setLineCap:kCGLineCapRound];
[line setLineJoin:kCGLineJoinRound];
line.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:pathToDraw];
line.physicsBody.dynamic = NO;
line.physicsBody.restitution = 1;
line.name = #"line";
[self addChild:line];
}
I can't seem to figure out how to prevent the physicsBody path from rejoining back to the beginning. Any help would be appreciated. Thanks!
The following code draws a temporary line (white) as you move your finger around the screen and then draws a final line (red) when you lift your finger. The code then adds a edge chain physics body to the line.
#implementation GameScene {
SKShapeNode *lineNode;
CGPoint startingPoint;
}
-(void)didMoveToView:(SKView *)view {
self.scaleMode = SKSceneScaleModeResizeFill;
}
- (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;
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;
finalLineNode.strokeColor = [SKColor redColor];
finalLineNode.lineWidth = 1;
finalLineNode.physicsBody = [SKPhysicsBody bodyWithEdgeChainFromPath:pathToDraw];
[self addChild:finalLineNode];
}
#end

SpriteKit Rendering Issue in iOS 8 for drawing app

I have a drawing simulation SKScene that works fine in iOS 7 that doesn't work in iOS 8. This is both for the simulator and the device.
The scene should show black lines where the finger touches the screen, and they should persist after you have finished "drawing" a line. Here's a screenshot of it in iOS 7:
Although there are no crashes, the lines don't render at all in iOS 8. I just get a blank canvas. NSLogging indicates that it does register the touchesBegan/Moved/Ended functions correctly.
I have produced the entire class in its entirety:
#implementation CSDraw
-(id)initWithSize:(CGSize)size type:(NSString *)CSType stresslevel:(NSInteger)stress_indicator { //designated initializer
if (self = [super initWithSize:size type: CSType stresslevel:stress_indicator]) {
NSLog(#"Creating new scene from CSDraw within the init");
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.swiped = NO;
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
self.pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(self.pathToDraw, NULL, positionInScene.x, positionInScene.y);
self.lineNode = [SKShapeNode node];
self.lineNode.path = self.pathToDraw;
self.lineNode.strokeColor = [SKColor blackColor];
self.lineNode.lineWidth = 10;
self.lineNode.zPosition = 50;
[self addChild:self.lineNode];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
self.swiped = YES;
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
CGPathAddLineToPoint(self.pathToDraw, NULL, positionInScene.x, positionInScene.y);
self.lineNode.path = self.pathToDraw;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
if(!self.swiped) { //user just tapped once, draw a single point
SKSpriteNode *dot = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(10, 10)];
dot.position = positionInScene;
[self addChild: dot];
} else { //calls touchesMoved
}
//[self.lineNode removeFromParent]; //comment out this line if you want line to remain on screen
CGPathRelease(self.pathToDraw);
}
#end
This class was written from the code I found in this StackOverFlow answer.
I had a similar problem with a Sprite Kit iOS8 game and fixed it with something like this: Try adding a CGPathMoveToPoint call immediately before the CGPathAddLineToPoint call in your touchesMoved function.
According to the class reference for CGPathAddLineToPoint, calling CGPathAddLineToPoint automatically "updates the current point to the specified location (x,y) [the new endpoint]". However, my lines weren't getting rendered correctly in iOS8 until I did this manually by calling CGPathMoveToPoint before every CGPathAddLineToPoint call. Not sure why this is. Maybe a bug with Sprite Kit in iOS8.
Please find below the modified code, with changes marked with a /* new */ comment. The code assumes that you have a CGPoint property called lastPointTouched.
#implementation CSDraw
-(id)initWithSize:(CGSize)size type:(NSString *)CSType stresslevel:(NSInteger)stress_indicator { //designated initializer
if (self = [super initWithSize:size type: CSType stresslevel:stress_indicator]) {
NSLog(#"Creating new scene from CSDraw within the init");
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.swiped = NO;
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
self.pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(self.pathToDraw, NULL, positionInScene.x, positionInScene.y);
/* new */ self.lastPointTouched = positionInScene;
self.lineNode = [SKShapeNode node];
self.lineNode.path = self.pathToDraw;
self.lineNode.strokeColor = [SKColor blackColor];
self.lineNode.lineWidth = 10;
self.lineNode.zPosition = 50;
[self addChild:self.lineNode];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
self.swiped = YES;
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
/* new */ CGPathMoveToPoint(self.pathToDraw, NULL, self.lastPointTouched.x, self.lastPointTouched.y);
CGPathAddLineToPoint(self.pathToDraw, NULL, positionInScene.x, positionInScene.y);
/* new */ self.lastPointTouched = positionInScene;
self.lineNode.path = self.pathToDraw;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
if(!self.swiped) { //user just tapped once, draw a single point
SKSpriteNode *dot = [SKSpriteNode spriteNodeWithColor:[SKColor blackColor] size:CGSizeMake(10, 10)];
dot.position = positionInScene;
[self addChild: dot];
} else { //calls touchesMoved
}
//[self.lineNode removeFromParent]; //comment out this line if you want line to remain on screen
CGPathRelease(self.pathToDraw);
}
#end

How to not run scenes in the background spritekit

I have a game with a menu scene, a play scene, and a game over scene. When I am on one of them is there a way to not run the others in the background. For example on my play scene when you make contact with something it switches to the game over scene. When I'm on the menu scene the play scene runs and when it makes contact it switches to the game over scene.
So My Question is: Can I make it so that the scene won't run in the background? Or a way to delay it until I press the play button on the menu?
Here is the code for the first scene:
#import "WEMenuScene.h"
#import "WEMyScene.h"
#implementation WEMenuScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.scaleMode = SKSceneScaleModeAspectFill;
SKSpriteNode* background = [SKSpriteNode spriteNodeWithImageNamed:#"landscape"];
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame));
background.zPosition = 1000;
[self addChild:background];
[self addChild:[self playButton]];
}
return self;
}
-(SKSpriteNode *) playButton {
SKSpriteNode* play = [SKSpriteNode spriteNodeWithImageNamed:#"Play"];
play.position = CGPointMake(CGRectGetMidX(self.frame), 300);
play.zPosition = 1200;
play.name = #"playButton";
return play;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode* node = [self nodeAtPoint:location];
if ([node.name isEqualToString:#"playButton"]) {
SKScene* playScene = [[WEMyScene alloc] initWithSize:self.size];
SKTransition* transitionPlay = [SKTransition doorsOpenVerticalWithDuration:0.5];
[self.view presentScene:playScene transition:transitionPlay];
}
}
#end
Here is the code for the second scene:
#import "WEMyScene.h"
#import "WECapturedScene.h"
#implementation WEMyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.scaleMode = SKSceneScaleModeAspectFill;
[self performSelector:#selector(logs) withObject:nil afterDelay:3.0];
[self performSelector:#selector(moveBackground) withObject:nil afterDelay:0.0];
[self addChild:[self createCharacter]];
[self setUpActions];
}
return self;
}
-(SKSpriteNode *) createCharacter {
SKSpriteNode* holly = [SKSpriteNode spriteNodeWithImageNamed:#"holly1"];
holly.position = CGPointMake(CGRectGetMidX(self.frame), 185);
holly.name = #"holly";
holly.zPosition = 40;
return holly;
}
-(void) logs {
CGPoint startPoint = CGPointMake(480, 175);
SKSpriteNode* logs = [SKSpriteNode spriteNodeWithImageNamed:#"log"];
logs.position = CGPointMake(startPoint.x, startPoint.y);
logs.name = #"logs";
logs.zPosition = 40;
[self addChild:logs];
float spawnLog = arc4random_uniform(3)+ 1.4;
[self performSelector:#selector(logs) withObject:nil afterDelay:spawnLog];
}
-(void) setUpActions {
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:#"Holly"];
SKTexture *movetex1 = [atlas textureNamed:#"holly1"];
SKTexture *movetex2 = [atlas textureNamed:#"holly2"];
SKTexture *movetex3 = [atlas textureNamed:#"holly3"];
SKTexture *movetex4 = [atlas textureNamed:#"holly4"];
SKTexture *movetex5 = [atlas textureNamed:#"holly5"];
SKTexture *movetex6 = [atlas textureNamed:#"holly6"];
SKTexture *movetex7 = [atlas textureNamed:#"holly7"];
NSArray *atlasTexture = #[movetex1, movetex2, movetex3, movetex4, movetex5, movetex6, movetex7];
SKAction* atlasAnimation =[SKAction repeatActionForever:[SKAction animateWithTextures:atlasTexture timePerFrame:0.08]];
hollyMovement = [SKAction sequence:#[atlasAnimation]];
SKSpriteNode* holly = (SKSpriteNode*)[self childNodeWithName:#"holly"];
holly.zPosition = 40;
[holly runAction:hollyMovement];
SKAction* moveUp = [SKAction moveByX:0 y:90 duration:0.50];
SKAction* wait = [SKAction moveByX:0 y:0 duration:0.4];
SKAction* moveDown = [SKAction moveByX:0 y:-90 duration:0.4];
SKAction* done = [SKAction performSelector:#selector(jumpDone) onTarget:self];
hollyUp = [SKAction sequence:#[moveUp, wait, moveDown, done]];
}
-(void) jumpDone {
isJumping = NO;
}
-(void) moveBackground {
CGPoint startPoint = CGPointMake(480, 230);
SKSpriteNode* landscape = [SKSpriteNode spriteNodeWithImageNamed:#"landscape"];
landscape.position = CGPointMake(startPoint.x, startPoint.y);
landscape.name = #"landscape";
landscape.zPosition = 1;
[self addChild:landscape];
float spawnbackground = 0.7;
[self performSelector:#selector(moveBackground) withObject:nil afterDelay:spawnbackground];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
if (isJumping == NO) {
isJumping = YES;
SKSpriteNode* holly = (SKSpriteNode*)[self childNodeWithName:#"holly"];
[holly runAction:hollyUp];
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
SKNode* holly = [self childNodeWithName:#"holly"];
[self enumerateChildNodesWithName:#"landscape" usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.x < 0 || node.position.y < 0) {
[node removeFromParent];
}else {
node.position = CGPointMake(node.position.x - 10, node.position.y);
}
}];
[self enumerateChildNodesWithName:#"logs" usingBlock:^(SKNode *node, BOOL *stop) {
if (node.position.x < 0 || node.position.y < 0) {
[node removeFromParent];
}else {
node.position = CGPointMake(node.position.x - 10, node.position.y);
}
if ([holly intersectsNode:node]) {
SKScene *capturedScene = [[WECapturedScene alloc] initWithSize:self.size];
SKTransition* transition = [SKTransition doorsOpenVerticalWithDuration:0.5];
[self.view presentScene:capturedScene transition:transition];
}
}];
[self enumerateChildNodesWithName:#"dogCatcher" usingBlock:^(SKNode *node, BOOL *stop) {
node.position = CGPointMake(node.position.x + 10, node.position.y);
}];
}
Here is the view controller:
#import "WEViewController.h"
#import "WEMyScene.h"
#import "WEMenuScene.h"
#implementation WEViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Configure the view.
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
// Create and configure the scene.
SKScene * scene = [WEMenuScene sceneWithSize:skView.bounds.size];
scene.scaleMode = SKSceneScaleModeAspectFill;
// Present the scene.
[skView presentScene:scene];
}
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return UIInterfaceOrientationMaskAllButUpsideDown;
} else {
return UIInterfaceOrientationMaskAll;
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
#end

How to place a tile by tapping on a isometric tiled map which uses CCLayerPanZoom class

I have a tiled map. I use cocos2D. The isometric map has an CCLayerPanZoom. For Zooming and scrolling. Now I want to add a tile at the position where I pressed it. It does not work. It is inserting the tile at the wrong position.
Does it has to do with the scaling of the map(Zooming and Scroling which is posible).?
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
CGPoint playerPos = _player.position;
CGPoint diff = ccpSub(touchLocation, playerPos);
if (abs(diff.x) > abs(diff.y)) {
if (diff.x > 0) {
playerPos.x += self.map.tileSize.width;
} else {
playerPos.x -= self.map.tileSize.width;
}
} else {
if (diff.y > 0) {
playerPos.y += self.map.tileSize.height;
} else {
playerPos.y -= self.map.tileSize.height;
}
}
//player.position = playerPos; // Todo: Trymove
if (playerPos.x <= (self.map.mapSize.width * self.map.tileSize.width) &&
playerPos.y <= (self.map.mapSize.height * self.map.tileSize.height) &&
playerPos.y >= 0 &&
playerPos.x >= 0 ) {
[self setPlayerPosition:playerPos];
}
if([TileMapLayer isOnTheMapMoreRestrictive:touchLocation map:self.map mapsize:self.map.mapSize.width] )
[self plantObject:touchLocation];
else
CCLOG(#"Outside possition");
[self setDotPosition: [self tilePosFromLocation:touchLocation tileMap:self.map]];
}
-(void)plantObject:(CGPoint) location{
punkt = [CCSprite spriteWithFile:#"tree.png"];
punkt. position = [self tilePosFromLocation:location tileMap:self.map];
[_map addChild:punkt z:4];
}

Cocos2d Shooting Method

ok i am new to coding and cocos2d
i have this shooting code that will fire a projectile and when i try to fire on the left side of the screen it the projectile is fired down and right from the position of the ball?
heres my GamePlay.m
#import "GamePlay.h"
CCSprite *player;
CCSprite *grass;
CCSprite *gameBg;
#implementation GamePlay
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
GamePlay *layer = [GamePlay node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init]))
{
self.isTouchEnabled = YES;
gameBg = [CCSprite spriteWithFile:#"backgroundGame1.png"];
gameBg.position = ccp(240,160);
[self addChild:gameBg];
grass = [CCSprite spriteWithFile:#"grass.jpg"];
grass.position = ccp(240,25);
[self addChild:grass];
player = [CCSprite spriteWithFile:#"ball.png"];
player.position = ccp(27,95);
[self addChild:player];
x = 5;
y = 5;
}
return self;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:[myTouch view]];
point = [[CCDirector sharedDirector] convertToGL:point];
if (point.x > 240 && point.y < 150)
{
[self unschedule:#selector(moveLeft)];
[self schedule:#selector(moveRight) interval:.01];
}
if (point.x < 240 && point.y < 150)
{
[self unschedule:#selector(moveRight)];
[self schedule:#selector(moveLeft) interval:.01];
}
NSLog(#"Touch Began");
// Choose one of the touches to work with
if (point.y > 150)
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGSize winSize = [[CCDirector sharedDirector]winSize];
CCSprite *projectile = [CCSprite spriteWithFile:#"projectile.png"];
projectile.position = ccp(player.position.x,player.position.y);
int offX = location.x - projectile.position.x;
int offY = location.y - projectile.position.y;
[self addChild:projectile];
int realX = winSize.width + (projectile.contentSize.width/2);
float ratio = (float) offY / (float) offX;
int realY = (realX *ratio) + projectile.position.y;
CGPoint realDest = ccp(realX, realY);
int offRealX = realX - projectile.position.x;
int offRealY = realY - projectile.position.y;
float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
float velocity = 480/1;
float realMoveDuration = length/velocity;
[projectile runAction:[CCMoveTo actionWithDuration:realMoveDuration position:realDest]];
NSLog(#"Shoot!");
}
}
-(void)ccTouchesEnded:(NSSet *) touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint point = [myTouch locationInView:[myTouch view]];
point = [[CCDirector sharedDirector] convertToGL:point];
[self unschedule:#selector(moveLeft)];
[self unschedule:#selector(moveRight)];
NSLog(#"Touch Ended");
}
-(void) spriteMoveFinished: (id) sender
{
}
-(void)moveLeft
{
player.position = ccp(player.position.x - x, player.position.y);
if (player.position.x < 15)
{
player.position = ccp(16,player.position.y);
}
}
-(void)moveRight
{
player.position = ccp(player.position.x + x, player.position.y);
if (player.position.x > 465)
{
player.position = ccp(464,player.position.y);
}
}
#end
this is the shooting method (i think it has something to do with the x & y offset?)
if (point.y > 150)
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CGSize winSize = [[CCDirector sharedDirector]winSize];
CCSprite *projectile = [CCSprite spriteWithFile:#"projectile.png"];
projectile.position = ccp(player.position.x,player.position.y);
int offX = location.x - projectile.position.x;
int offY = location.y - projectile.position.y;
[self addChild:projectile];
int realX = winSize.width + (projectile.contentSize.width/2);
float ratio = (float) offY / (float) offX;
int realY = (realX *ratio) + projectile.position.y;
CGPoint realDest = ccp(realX, realY);
int offRealX = realX - projectile.position.x;
int offRealY = realY - projectile.position.y;
float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
float velocity = 480/1;
float realMoveDuration = length/velocity;
[projectile runAction:[CCMoveTo actionWithDuration:realMoveDuration position:realDest]];
NSLog(#"Shoot!");
}
The best resource is here
Just give it a try.
Cheers
I found the answer here Projectiles/Bullets direction Cocos2d
you needed to do this,
// After adding the projectile:
[self addChild:projectile];
// Add a scalar float:
float scalarX = 1.0f;
// And make it negative if the touch is left of the character:
if (offX < 0.0f) scalar = -1.0f;
// Then just multiply the realX by this scalar to make it point the correct way
int realX = scalar * (winSize.width + (projectile.contentSize.width/2));

Resources