我被要求簡化這個問題,所以這就是我正在做的。SpriteKit關節:跟着身體
我在SpriteKit的物理關節(以及可能的物理屬性)中掙扎。我試過每一個子類和許多配置,但接縫沒有任何作用,或者我做錯了什麼。
我正在開發貪吃蛇遊戲。用戶控制蛇頭前進,並以正向速度向前移動,用戶可以將其順時針或逆時針旋轉。所有剩下的蛇的碎片應該跟隨頭部 - 他們應該旅行完全相同的路徑,頭部是前一段時間。
我認爲對於這個遊戲Pin聯合應該是答案,哪個錨點恰好在元素之間的中心。
不幸的是,結果並不完美。結構應該是完美的圓形,但它不是。我附上了代碼,顯示了當前效果的gif。有沒有人有足夠的經驗給我任何建議物理身體和/或關節的屬性應該在這裏適用於預期的效果?
我的代碼:
class GameScene: SKScene {
private var elements = [SKNode]()
override func didMove(to view: SKView) {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
let dummyTurnNode = SKNode()
dummyTurnNode.position = CGPoint(x: size.width/2 - 50, y: size.height/2)
let dummyTurnBody = SKPhysicsBody(circleOfRadius: 1)
dummyTurnBody.isDynamic = false
dummyTurnNode.physicsBody = dummyTurnBody
addChild(dummyTurnNode)
for index in 0..<5 {
let element = SKShapeNode(circleOfRadius: 10)
let body = SKPhysicsBody(circleOfRadius: 10)
body.linearDamping = 0
// body.mass = 0
element.physicsBody = body
element.position = CGPoint(x: size.width/2, y: size.height/2 - 30 * CGFloat(index))
elements.append(element)
addChild(element)
let label = SKLabelNode(text: "A")
label.fontSize = 10
label.fontName = "Helvetica-Bold"
element.addChild(label)
if index == 0 {
element.fillColor = UIColor.blue()
body.velocity = CGVector(dx: 0, dy: 30)
let dummyTurnJoint = SKPhysicsJointPin.joint(withBodyA: dummyTurnBody, bodyB: body, anchor: dummyTurnNode.position)
physicsWorld.add(dummyTurnJoint)
} else {
body.linearDamping = 1
element.fillColor = UIColor.red()
let previousElement = elements[index - 1]
let connectingJoint = SKPhysicsJointPin.joint(withBodyA: previousElement.physicsBody!, bodyB: body, anchor: CGPoint(x: size.width/2, y: size.height/2 - 30 * CGFloat(index) + CGFloat(15)))
physicsWorld.add(connectingJoint)
}
}
}
override func update(_ currentTime: TimeInterval) {
let head = elements.first!.physicsBody!
var velocity = head.velocity
velocity.normalize()
velocity.multiply(30)
head.velocity = velocity
}
}
extension CGVector {
var rwLength: CGFloat {
let xSq = pow(dx, 2)
let ySq = pow(dy, 2)
return sqrt(xSq + ySq)
}
mutating func normalize() {
dx /= rwLength
dy /= rwLength
}
mutating func multiply(_ factor: CGFloat) {
dx *= factor
dy *= factor
}
}
你使用的是什麼Swift版本? –
@AlessandroOrnano 3 –