在以点为中心时阻止碰撞时的运动

时间:2016-08-01 09:16:07

标签: ios swift sprite-kit accelerometer

我正在制作一款小型游戏,其中使用iPhone加速度计在2D世界中移动角色。向左或向右倾斜手机不会移动角色的x位置,但是世界其他地方,每个"层"世界上有不同的速度。

我的问题是我希望我的角色"停止" (当世界其他地方遇到障碍时)。

这是我到目前为止所提出的。

let motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.1
motionManager.startAccelerometerUpdates()

// the (fixed) x position of the character 
let startingPositionX: CGFloat = 150

// in the "update()" function of the SKScene
if let accelerometerData = motionManager.accelerometerData { 
    // the x part of the acceleration (the iphone is sideways)
    let acc = CGFloat(accelerometerData.acceleration.y)
    // the character 
    let hero = self.childNodeWithName("hero") as! Hero

    // when the hero "touches" a block, it slightly pushes it back
    let deltaX = startingPositionX - hero.position.x

    if abs(acc) > 0.05 { 
        let accNorm = max(acc, 0) * CGFloat(deltaX <= 0) + 
                      min(acc, 0) * CGFloat(deltaX >= 0)
        // this method moves all the sprites of the scene by their defined quantity
        // (foreground being faster than background)
        self.spriteManager.update(accNorm)
    }
    // put the character back in its original position
    hero.position.x = startingPositionX
}

现在感觉非常 hackish,它几乎&#34;虽然行hero.position.x = startingPositionX被调用,但是由于某种原因,角色有时无法回到原来的位置。这使得deltaX始终非零并阻止一个方向的移动。

我不知道如何使用碰撞来实现这一点,我看到的唯一其他解决方案是更改逻辑并使用某种类型的相机,这会产生不同节点层的视差效果实施起来要困难得多。可能有更好的方法吗?

0 个答案:

没有答案