我在屏幕上有一个会逐渐变大的圆圈(顺便说一句,Balloon类是SKShapeNode的一种)。在touches中,我单击了圆圈,并打印出我触摸过的圆圈,但是没有施加任何脉冲。我如何找到问题?我是SpriteKit的新手。
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var radius = 40.0
var balloon : Balloon? = nil
override func didMove(to view: SKView) {
balloon = Balloon(radius: radius, position: CGPoint(x: frame.midX, y: frame.minY + 250))
balloon?.name = "balloon"
let physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(radius))
physicsBody.affectedByGravity = false
balloon?.physicsBody = physicsBody
balloon?.physicsBody?.isDynamic = true
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
self.addChild(balloon!)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let node : SKNode = self.atPoint(location)
if node.name == "balloon" {
print("touching balloon.")
balloon?.physicsBody?.applyImpulse(CGVector(dx: 10.0, dy: 10.0), at: location)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
radius += 0.05
self.balloon?.radius = radius
let physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(radius))
physicsBody.affectedByGravity = false
balloon?.physicsBody = physicsBody
balloon?.physicsBody?.isDynamic = true
}
}
最佳答案
您每次更新都会创建一个新的主体。如果要给气球充气,请使用比例尺:
var scale = 1.0
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
scale += 0.05
self.balloon?.setScale(scale)
}
这样一来,您的物理身体便可以施加脉冲,因为您不会在每次更新时都创建一个新的身体。
关于ios - applyImpulse在接触节点时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51637709/