按下时使球弹起

时间:2019-02-16 21:14:02

标签: swift sprite-kit

我正在尝试制作一个游戏,您可以使用SpriteKit单击一个球。此刻,我可以在屏幕上的任意位置单击,球会向上移动。

我希望它仅在单击球时移动或反弹。我在做什么错了?

import SpriteKit
import GameplayKit


class GameScene: SKScene {

    var ball = SKSpriteNode()
    var grass = SKSpriteNode()


    override func didMove(to view: SKView) {
        ball = (self.childNode(withName: "ball") as? SKSpriteNode)!

        let border = SKPhysicsBody(edgeLoopFrom: self.frame)
        border.friction = 0
        border.restitution = 1
        self.physicsBody = border
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { self.touchDown(atPoint: t.location(in: self)) }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { self.touchUp(atPoint: t.location(in: self)) }
    }

    func touchDown(atPoint pos: CGPoint) {
        jump()
    }
    func touchUp(atPoint pos: CGPoint) {
        ball.texture = SKTexture(imageNamed: "football-161132_640")
    }


    func jump() {
        ball.texture = SKTexture(imageNamed: "football-161132_640")
        ball.physicsBody?.applyImpulse(CGVector(dx: Int.random(in: -5...5), dy: 80))
    }
}

1 个答案:

答案 0 :(得分:1)

多次触摸:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if ball.contains(location) {
            jump()
        }
    }
}

单点触摸:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.location(in: self)
        if ball.contains(location) {
            jump()
        }
    }
}