每次触摸SKNode时如何添加1点

时间:2016-08-07 00:54:41

标签: swift sprite-kit touch sknode

我创造了一个涉及落球的游戏。每次球员击球时,他们都应该获得一分。我设置了分数标签,但它只保持在0.

我的代码有问题吗?

我使用 GameElements.swift 文件作为扩展程序。这是文件:

     {
         Shirt s1 = new Shirt();
         Shirt s2 = s1;
         s1.size = 'S';
         System.out.println(s1.size); //S
         System.out.println(s2.size); //S

     }

这是 GameScene.swift 文件:

extension GameScene {
    //1st Ball//
    func createPlayer() -> SKNode {

        let playerNode = SKNode()
        playerNode.position = CGPoint(x:self.size.width / 2, y:440)

        let sprite = SKSpriteNode(imageNamed: "Ball")
        sprite.name = "ballPoints"
        playerNode.addChild(sprite)

        playerNode.physicsBody = SKPhysicsBody(circleOfRadius: 120)

        playerNode.physicsBody?.dynamic = true
        playerNode.physicsBody?.allowsRotation = false

        playerNode.physicsBody?.restitution = 3
        playerNode.physicsBody?.friction = 0
        playerNode.physicsBody?.angularDamping = 0
        playerNode.physicsBody?.linearDamping = 0

        playerNode.physicsBody?.usesPreciseCollisionDetection = true


        playerNode.physicsBody?.categoryBitMask = CollisionBitMask.Player

        playerNode.physicsBody?.categoryBitMask = 0

        return playerNode
    }
}

我知道这是很多代码,但我希望专家能够自己测试代码。作为背景,我正在学习本教程:https://www.youtube.com/watch?v=0gOi_2Jwt28直到某一点。

enter image description here 最好的问候,乔丹

1 个答案:

答案 0 :(得分:2)

第1步

首先,让我们为Ball

创建一个类
class Ball: SKSpriteNode {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let scene = self.scene as! GameScene
        scene.score += 1
    }
}

第2步

然后在createPlayer()内,让我们替换

let sprite = SKSpriteNode(imageNamed: "Ball")

用这个

let sprite = Ball(imageNamed: "Ball")
sprite.userInteractionEnabled = true

第3步

让我们从touchesBegan删除GameScene

更新

此代码正在按预期工作

class GameScene: SKScene {

    var scoreLabel: SKLabelNode!
    var ball: Ball!
    private var score = 0 {
        didSet {
            scoreLabel.text = "\(score)"
            print(score)

        }
    }

    override func didMoveToView(view: SKView) {
        let ball = Ball()
        ball.position = CGPoint(x:frame.midX, y: frame.midY)
        addChild(ball)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // this is called when you tap outside of the Ball
        // use self.ball to make the ball to jump
    }
}

class Ball: SKSpriteNode {

    init() {
        let texture = SKTexture(imageNamed: "ball")
        super.init(texture: texture, color: .clearColor(), size: texture.size())
        userInteractionEnabled = true
    }


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let scene = self.scene as! GameScene
        scene.score += 1
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

enter image description here