swift - Spritekit 坐标系意外定位

标签 swift sprite-kit coordinate

我有类 AttackArea、Player 和 GameScene。 我想实例化一个新的 AttackArea 对象并将其放置在玩家附近,具体取决于面对的玩家。现在我在正确定位方面遇到了问题。如果我将 AttackArea 添加为 GameScene 的子项,则定位会按预期工作。但如果我这样做,AttackArea 就不会随着玩家移动。否则,如果我将 AttackArea 添加为 Player 的子项,它会随着 Player 一起移动。这正是我想要的。这里的问题是 AttackArea 的定位现在离 Player 很远。这是 Player 类中的代码:

func attack(){
    let attack = AttackArea(color: .red, size: CGSize(width: self.frame.width, height: self.frame.height / 2))
    var animation = ""
    switch playerFacing{
    case .back:
        attack.position = CGPoint(x: self.position.x, y: self.position.y + 40)
        animation = Constants.Actions.playerAttackBack
    case .front:
        attack.position = CGPoint(x: self.position.x, y: self.position.y - 40)
        animation = Constants.Actions.playerAttackFront
    case .left:
        attack.position = CGPoint(x: self.position.x - 40, y: self.position.y)
        animation = Constants.Actions.playerAttackLeft
    case .right:
        attack.position = CGPoint(x: self.position.x + 40, y: self.position.y)
        animation = Constants.Actions.playerAttackRight
    case .none:
        break
    }
    attack.zPosition = self.zPosition + 1
    attack.setup()
    if animation != ""{
        self.run(SKAction(named: animation)!)
    }
    self.addChild(attack)
}

第一张图片显示了 AttackArea 是 GameScene 的子项时的情况。定位很好,但我希望它成为 Player 的子级。

enter image description here

第二张图是AttackArea是Player的 child 时的定位。右上角的红色方 block 是AttackArea,红色圆圈是Player。

enter image description here

在这种情况下,为什么 AttackArea 离 Player 这么远?我如何才能获得与第一张图片相同的结果,唯一的异常(exception)是 AttackArea 是 Player 的子区域?

最佳答案

如果你改变定位会发生什么

switch playerFacing{
    case .back:
        attack.position = CGPoint(x: 0, y: 0 + 40)
        animation = Constants.Actions.playerAttackBack
    case .front:
        attack.position = CGPoint(x: 0, y: 0 - 40)
        animation = Constants.Actions.playerAttackFront
    case .left:
        attack.position = CGPoint(x: 0 - 40, y: 0)
        animation = Constants.Actions.playerAttackLeft
    case .right:
        attack.position = CGPoint(x: 0 + 40, y: 0)
        animation = Constants.Actions.playerAttackRight
    case .none:
        break
    }

我怀疑您的玩家(例如)可能位于位置 500、500,并且您正在将这些值重新添加到攻击位置,所以现在它的位置是 1000、1040

关于swift - Spritekit 坐标系意外定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47380978/

相关文章:

swift - 如何在始终面向前方移动时旋转 Spritenode?

system - 将表示从一个坐标系旋转到另一个坐标系的四元数转换

ios - 通过异步调用问题将数据加载到数组中(Geofire、Swift)

swift - 在 Swift 3 中从解析流式传输音频

ios - 如何以编程方式在 Spritekit 中截取屏幕截图?

ios - 在 Swift 中创建一个线性重力场

ios - 刷新表格时如何取消初始化 UITableViewCell 实例?

swift - 具有继承错误的泛型

java - 无法在不同类别中使用值(value)

C# 坐标键字典