Sprite Kit:如何创建一个节点" jump"并根据节点位置和触摸长度向左或向右移动?

时间:2014-05-12 04:58:28

标签: ios sprite-kit

这是我的第一篇文章,所以请轻松哈哈。

我是iOS'的新手。 '编码',' Xcode'和' spritekit'。我想制作一个图像节点"跳跃"如果我触摸屏幕上的任何地方,正y轴上的距离,但如果我触摸左侧或右侧的某个地方,如果图像并保持一定时间,它会在相应的左或右方向上移动,相应的距离为触摸的长度。

不确定这是否非常清楚,但任何帮助都将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:0)

你可以像这样移动一个节点

在touchesEnded:或touchesBegan:方法:

{
node.position.y += 50;
}

为了让精灵移动到某个地方你也可以使用动作,有一系列的动作,如moveTo动作。

我建议选择一本关于精灵工具包的教程或书籍。有免费教程的好网站是raywenderlich.com

答案 1 :(得分:-2)

请尝试以下代码:

精灵移动:根据您在屏幕上任意位置的触摸方向左/右

  // CGPoint initialPos; // in .h file

  -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *touch = [touches anyObject];
     CGPoint touchPt = [touch locationInView:touch.view];
     initialPos = [[CCDirector sharedDirector] convertToGL:touchPt];
  }
  -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *myTouch=[touches anyObject];
     CGPoint currentPos=[myTouch locationInView:[myTouch view]];
     currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];

     float diffX = currentPos.x - initialPos.x;
     float diffY = currentPos.y - initialPos.y;

     CGPoint velocity = ccp(diffX, diffY);
     initialPos = currentPos;
     [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
  }

  - (void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
  {
     UITouch *myTouch=[touches anyObject];
     CGPoint currentPos=[myTouch locationInView:[myTouch view]];
     currentPos=[[CCDirector sharedDirector] convertToGL:currentPos];
     float diffX = currentPos.x - initialPos.x;
     float diffY = currentPos.y - initialPos.y;
     CGPoint velocity = ccp(diffX, diffY);
     initialPos = currentPos;
     [Sprite setPosition:ccpAdd([SmileBall position], velocity)];
  }

精灵跳跃:根据你的触摸屏幕

  -(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
  {
     CCSprite *RunningChar;
     RunningChar=(CCSprite *)[self getChildByTag:10];
     UITouch *touch = [touches anyObject];
     CGPoint touchPt = [touch locationInView:touch.view];
     touchPt = [[CCDirector sharedDirector] convertToGL:touchPt];

     float radian = ccpToAngle(ccpSub(touchPt, prevPoint));
     float degrees = CC_RADIANS_TO_DEGREES(radian);

     if (degrees >= 22.5 && degrees <= 112.5) // for upward direction :). otherwise you can write only code without ant condition
     {
         CCJumpTo *jump=[CCJumpTo actionWithDuration:0.7 position:CGPointMake(RunningChar.position.x, 87) height:110 jumps:1];
         [RunningChar runAction:seq];
     }
     else
     {

     }
  }

试试这个:)