我创造了一个涉及落球的游戏。每次球员击球时,他们都应该获得一分。我设置了分数标签,但它只保持在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直到某一点。
答案 0 :(得分:2)
首先,让我们为Ball
class Ball: SKSpriteNode {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let scene = self.scene as! GameScene
scene.score += 1
}
}
然后在createPlayer()
内,让我们替换
let sprite = SKSpriteNode(imageNamed: "Ball")
用这个
let sprite = Ball(imageNamed: "Ball")
sprite.userInteractionEnabled = true
让我们从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")
}
}