swift - SpriteKit - 将点转换为场景坐标会给出错误的值

标签 swift casting sprite-kit skphysicsworld

我想将单元位置转换为场景坐标。目前,该单元是一个不可见节点的子节点。当细胞与病毒接触时,我就得到了细胞的位置。令人困惑的是,单元相对于其父单元的坐标以及坐标转换到场景时的位置都是相同的。位置读数为 (0,0.002),但其实际位置应为 (0,50)。

如果我通过直接引用单元节点来监视位置(例如 childNodeWithName("cell")),它会显示正确的位置。我最初认为这个问题与向下转换有关,但无论有没有它,位置都会显示不正确。为什么会这样?

func didBeginContact(contact: SKPhysicsContact) {
    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    if bodyA.categoryBitMask & PhysicsCategory.Virus != 0
        && bodyB.categoryBitMask & PhysicsCategory.Cell != 0 {

        let virus = bodyA.node as! VirusNode
        virus.attachedCell = bodyB.node as? CellNode
        print(self.convertPoint(virus.attachedCell!.position, toNode: self)) //outputs (0,0.002)
    }
}

最佳答案

您在要转换为 (self) 的同一个对象 (self) 上使用 ConvertPoint 方法,因此您将始终获得相同的点!

这段代码有很多问题。例如,简单设置virus的attachedCell属性不会使该病毒成为该病毒的子节点。

如果您想这样做,则必须明确地这样做。否则,该单元仍然是它之前所在节点的子节点...

你想要这个:

func didBeginContact(contact: SKPhysicsContact) {
    let bodyA = contact.bodyA
    let bodyB = contact.bodyB

    if bodyA.categoryBitMask & PhysicsCategory.Virus != 0
        && bodyB.categoryBitMask & PhysicsCategory.Cell != 0 {
        bodyB.node.removeFromParent()
        let virus = bodyA.node as! VirusNode
        virus.attachedCell = bodyB.node as? CellNode
        virus.addChild(bodyB.node)
        print(virus.convertPoint(virus.attachedCell!.position, toNode: self)) //should output properly
    }
}

这会将细胞的位置从病毒坐标系转换为场景坐标系。

关于swift - SpriteKit - 将点转换为场景坐标会给出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37076882/

相关文章:

ios - 使用开关控制流从函数推断返回类型

swift - SKSprite节点链

java.lang.ClassCastException : class org. openqa.selenium.By$ByXPath 无法转换为类 org.openqa.selenium.WebElement

ios - 未调用 MFMailComposeViewController

ios - 在 MKMapViewDelegate 中执行代码之前设置一个计时器

ios - 是什么让 UITableView 表现得像这样

java - 我什么时候必须沮丧一些事情?

swift - 将 acceptMouseMovedEvents 用于带有 Storyboard和 Swift 的 SpriteKit 鼠标操作

swift - 这个错误 (NSInvalidArgumentException) 是什么意思?

ios - 为什么第二个 MKPointAnnotation 不显示?