我有SKSpriteNode因爲self.physicsWorld.gravity = CGVectorMake(0.0, -4.0);
而被迫落地。當用戶在顯示屏上點擊並按住它時,我想讓SKSpriteNode飛起來,在用戶停止觸摸後,它再次落到地面上。SpriteKit SKSpriteNode觸摸並保持速度
我曾試圖改變速度,但它纔有小幅反彈,像applyImpulse方法...:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
flyingObject.physicsBody.velocity = CGVectorMake(0, 100)
}
}
編輯:
這裏是我的場景的初始化代碼
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// Physics
self.physicsWorld.gravity = CGVectorMake(0.0, -4.0);
// flyingObject
var flyingObjectTexture = SKTexture(imageNamed:"flyingObject")
flyingObject.filteringMode = SKTextureFilteringMode.Nearest
flyingObject = SKSpriteNode(texture: flyingObjectTexture)
flyingObject.setScale(1)
flyingObject.position = CGPoint(x: self.frame.size.width * 0.35, y: self.frame.size.height * 0.6)
flyingObject.physicsBody = SKPhysicsBody(circleOfRadius:flyingObject.size.height/2.0)
flyingObject.physicsBody.dynamic = true
flyingObject.physicsBody.allowsRotation = false
self.addChild(flyingObject)
// Ground
var groundTexture = SKTexture(imageNamed:"Ground")
var sprite = SKSpriteNode(texture:groundTexture)
sprite.setScale(0.5)
sprite.position = CGPointMake(self.size.width/2 - 100, sprite.size.height)
self.addChild(sprite)
var ground = SKNode()
ground.position = CGPointMake(0, groundTexture.size().height/2)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.width, groundTexture.size().height * 0.5))
ground.physicsBody.dynamic = false
self.addChild(ground)
}
您應該使用applyImpulse方法,而不是直接設置速度。從Apple的文檔中,「當一個物體在模擬中時,速度根據施加在身體上的力進行調整更爲常見。」 – 0x141E
這仍然只是讓對象彈起,而我需要它不斷地向上,直到用戶停止觸摸 –
要做到這一點,可以使用applyForce方法使用以下步驟:1)在touchesBegan中,標識並設置一個指向節點的指針如果選擇了一個節點(即,指針不是零),3)在touchesEnded中,將指針設置爲零,用戶選擇,2)更新:(NSTimeInterval)currentTime,applyForce。 – 0x141E