0
我想使用Swift在Xcode中製作一個簡單的平臺遊戲,這樣當我按住屏幕的左側時,它會不斷向左移動,直到放開,反之亦然。我已經添加了跳轉功能,但如果您有任何其他建議,我願意接受建議。如何使用觸控快速製作角色控制器?
這裏是我的GameController.swift代碼: 進口SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
let character = SKSpriteNode(imageNamed:"square.png")
let block = SKSpriteNode(imageNamed: "square.png")
override func didMoveToView(view: SKView) {
/* Setup your scene here */
//Physics
self.physicsWorld.gravity = CGVectorMake(0.0, -5.0)
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
//Character
character.position = CGPoint(x:CGRectGetMidX(self.frame),
y:CGRectGetMidY(self.frame))
character.setScale(0.25)
character.physicsBody = SKPhysicsBody(rectangleOfSize: character.size)
self.addChild(character)
//block
block.position = CGPoint(x: CGRectGetMidX(self.frame), y:
CGRectGetMidY(self.frame)*0.3)
block.setScale(0.2)
block.physicsBody = SKPhysicsBody(rectangleOfSize: block.size)
block.physicsBody?.dynamic = false
self.addChild(block)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch:AnyObject in touches {
let location = touch.locationInNode(self)
if location.x < CGRectGetMidX(self.frame) && location.y <
CGRectGetMidY(self.frame)*0.7{
character.physicsBody?.applyImpulse(CGVector(dx: -50, dy: 0))
} else if location.x > CGRectGetMidX(self.frame) && location.y <
CGRectGetMidY(self.frame)*0.7{
character.physicsBody?.applyImpulse(CGVector(dx: 50, dy: 0))
} else if location.y > character.position.y + 15 {
character.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
}
func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
}
func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
}
}
只要有它,當觸摸位置在touchesBegan位於屏幕的左側時(例如),開始一個永遠運行的SKAction,將字符向左移動,直到觸摸被釋放 - 在' touchesEnded',移除SKAction。這同樣適用於屏幕的右半邊,等等。有意義還是你希望我發佈一個完整的答案? - 這就是你問的,對吧? – Dopapp
是否有任何特定的原因,你在'physicsBody'上使用'.applyImpulse'而不是添加'SKAction'? – Dopapp
我不知道還有什麼是我真正的唯一原因... –