WorldNode与对象产生冲突

时间:2016-02-10 01:45:58

标签: swift object sprite-kit swift2

这个问题参考了这个问题:

Object positioning is off

所以我再次实现了代码:

let xAxisSpawnLocations: [CGFloat] = {

    var spawnLocations:[CGFloat] = []

    //Create 5 possible spawn locations
    let numberOfNodes = 5

for i in 0...numberOfNodes - 1 {

    /*
        Spacing between nodes will change if:

        1) number of nodes is changed,
        2) screen width is changed,
        3) node's size is changed.
    */

    var xPosition = (frame.maxX - player.size.width) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

    //add a half of a player's width because node's anchor point is (0.5, 0.5) by default
    xPosition += player.size.width/2.0

    spawnLocations.append( xPosition )
}

return spawnLocations
 }()

print(xAxisSpawnLocations)

        player.position = CGPoint(x: xAxisSpawnLocations[0], y: yAxisSpawnLocations[0])
        player.zPosition = 10
        addChild(player)

        //Fill one row (horizontally) right above the player with green frogs

        for xLocation in xAxisSpawnLocations {

           let greenFrog = SKSpriteNode(color: .greenColor(), size: player.size)
           greenFrog.position = CGPoint(x: xLocation, y: yAxisSpawnLocations[0])
           greenFrog.zPosition = 9000
           addChild(greenFrog)
        }

         player.position = CGPoint(x: xAxisSpawnLocations[1], y: yAxisSpawnLocations[0])

    }

这次正确的方式,我得到了这个:

The second time

因此玩家仍然不符合对象,并且由于某种原因它只会在屏幕的右侧产生。这是因为我有一个worldNode可以保存所有内容,并且相机位置位于worldNode中的Sprite上。 (这就是我的结论)

worldNode保存在worldNode中具有起始点(0,0)的玩家,并且它还保存保存对象的等级单位。摄像机位置以播放器节点(位于worldNode中)为中心

我正在尝试让对象在levelUnit上生成,而不仅仅是在它的一侧。

我将提供以下代码:

玩家的起始位置:

let startingPosition:CGPoint = CGPointMake(0, 0)

woldNode代码:

let worldNode:SKNode = SKNode()

//creates the world node point to be in the middle of the screen
self.anchorPoint = CGPointMake(0.5, 0.5)
addChild(worldNode)

//adds the player as a child node to the world node 
worldNode.addChild(thePlayer)
thePlayer.position = startingPosition
thePlayer.zPosition = 500   

相机定位代码:

override func didSimulatePhysics() {

self.centerOnNode(thePlayer) 
}

//centers the camera on the node world.

func centerOnNode(node:SKNode) {

let cameraPositionInScene:CGPoint = self.convertPoint(node.position, fromNode: worldNode)
worldNode.position = CGPoint(x: worldNode.position.x , y:worldNode.position.y - cameraPositionInScene.y  )

 }

我尝试在定位代码中使用levelUnit(包含对象),但它仍然不起作用。

有人可以告诉我我做错了什么。

1 个答案:

答案 0 :(得分:1)

问题出在以下几行:

var xPosition = (frame.maxX - player.size.width) / CGFloat((numberOfNodes - 1)) * CGFloat(i)

i的值从0到numberOfNodes-1。这意味着xPosition从0变为某个正数。但是,正如您所说,相机位于(0,0),所以所有绿色的青蛙都会被放置在相机的右侧。您需要数学结束,以便第一只青蛙靠近-frame.maxX/2,最后一只靠近+frame.maxX/2。简单(或懒惰)的方法是从结果中减去这个。即

xPosition -= frame.maxX/2