精灵互相追随

时间:2015-12-08 19:06:29

标签: swift sprite-kit

提前致谢。我目前有一个由设备倾斜控制的精灵,并希望每隔一段时间(NSTimer)让另一个精灵出现在它后面跟着它具有相同的物理特性。我有它设置,但我需要每秒更新的位置,所以它跟在它后面。我该怎么做?这就是我尝试过/做过的事。

    let snakeBodyY = snakeHead.position.y - 5
    let snakeBodyX = snakeHead.position.x - 5

    snakeHead = SKSpriteNode(imageNamed: "snakeHead")
    snakeHead.size = CGSize(width: 60, height: 60)
    snakeHead.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 50)
    self.addChild(snakeHead)

    snakeBody = SKSpriteNode(imageNamed: "snakeBody")
    snakeBody.size = CGSize(width: 50, height: 50)
    snakeBody.position.x = snakeBodyX
    snakeBody.position.y = snakeBodyY
    self.addChild(snakeBody)

1 个答案:

答案 0 :(得分:0)

取决于您需要的进步,

如果这是一个自由范围的2D世界,你可以将每个新的身体分配给尾部,使得位置相对于蛇,并且总是试图让身体部位移动到前一个身体部位的中心,直到头。

像这样设置你的精灵:

let snake = SKNode...
let head = SKSpriteNode...
let tail = SKSpriteNode...

//make sure you set up your positions for each body part, they should be relative to snake, not the screen

//setup collision so that tail and head can collide
head.physicsBody = SKPhysicsBody...
head.categoryBitMask = 1
head.collisionBitMask = 1
tail.physicsBody = SKPhysicsBody...   
tail.categoryBitMask = 1
tail.collisionBitMask = 1

//setup restitution so that they do not bounce when colliding
head.restitution = 0
tail.restitution = 0

//add the parts to snake
snake.addChild(head)
snake.addChild(tail)

//Now you have a snake with a head and tail create an action to move the snake tail to the center of head

let moveToCenter = SKAction.moveTo(head.position, duration:0)
tail.runAction(moveToCenter)

//this will move the talk to try to get to the center of head,  but collision physics will stop it from overlapping.

//Now everytime you want to add a new body
let body = SKSpriteNode...
body.physicsBody = SKPhysicsBody...
body.categoryBitMask = 1
body.collisionBitMask = 1
body.restitution = 0
snake.addChild(body)
let moveToCenter = SKAction.moveTo(tail.position, duration:0)
body.runAction(moveToCenter)
tail = body   //lets make the tail the new piece to add

//Then on every update loop. you want to go through the children and do something like this
let previousChild = head
for child in snake.children
{
  if child == head 
  {
    continue;
  }
  child.removeAllActions()
  let moveToCenter = SKAction.moveTo(previousChild.position, duration:0)
  child.runAction(moveToCenter)
  previousChild = child
}

现在,如果您发现此代码可能最终对您来说运行缓慢,并且不介意采用更加僵硬的方法,那么您也可以查找SKAction.followPath。现在我不打算详细介绍这些细节,但基本上你需要做的就是记录你的蛇是如何移动的,然后用它生成一条路径,并使用SKAction.followPath使所有身体部位沿着路径。

如果你在一个仅允许垂直和水平移动的二维平铺世界中工作,你可以创建一个精灵阵列,每当你的蛇进行一次移动时,你就会沿着蛇走下去并将它的位置改为前一个身体零件位置

相关问题