我有两个功能,一个叫球属性 - 设置()和发射():我请ball.launchSpriteKit类分离问题
var ball = Ball()
()后,我想知道它在哪里上x轴使用:
ball.position.x
但由于某种原因,我一直收到零。现在,我从touchesBegan
启动球并试图获得touchesEnded
的位置。正如我所说,启动部分工作正常。球出现了,并且如预期的那样弹跳了,但是在那之后我没做任何球属性有任何影响。下面是完整的代码:
Ball.swift
class Ball: SKSpriteNode {
var ball: SKSpriteNode!
func setUp(parentNode: SKNode) {
ball = SKSpriteNode(imageNamed: "ball2")
ball.name = "ball"
ball.position = CGPoint(x: 20, y: 200)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
ball.physicsBody?.restitution = 0
ball.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
ball.physicsBody?.categoryBitMask = PhysicsCategories.Ball
ball.physicsBody?.collisionBitMask = PhysicsCategories.Edge
ball.physicsBody?.contactTestBitMask = PhysicsCategories.Edge
parentNode.addChild(ball)
}
func launch() {
ball.physicsBody?.applyImpulse(CGVector(dx: 25, dy: 0))
}
}
GameScene.swift
import SpriteKit
import GameplayKit
struct PhysicsCategories {
static let Ball: UInt32 = 0
static let Edge: UInt32 = 0b1
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var ball = Ball()
override func didMove(to view: SKView) {
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 1
physicsBody = border
border.categoryBitMask = PhysicsCategories.Edge
border.collisionBitMask = PhysicsCategories.Ball
border.contactTestBitMask = PhysicsCategories.Ball
physicsWorld.contactDelegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
ball.setUp(parentNode: self)
ball.launch()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
print(ball.position.x) //value is always zero
}
func didBegin(_ contact: SKPhysicsContact) {
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch collision {
case PhysicsCategories.Ball | PhysicsCategories.Edge:
ball.removeFromParent() //doesn't get removed
default:
break
}
}
}