我正在尝试使用Xcode 10.1和Swift 4.2构建我的第一个基于SpriteKit的游戏。现在,我只是想让redBall在屏幕周围和边缘弹起。接下来我将添加blueBall。此时没有用户交互,我只希望球反弹并立即碰撞。
但是,我正在尝试以运动中的redBall开始,但这没有用。我尝试设置速度,施加力和施加脉冲。我尝试将redBall的质量及其摩擦设置为0.0。我知道我的游戏中的物理原理是可以正常工作的。如果我打开重力,球会掉到底部边缘,弹跳并停下来。
我认为我缺少一些简单的东西,但是我无法弄清楚那是什么。
import SpriteKit
enum PhysicsCategory {
static let none: UInt32 = 0
static let redBall: UInt32 = 0x1 << 0
static let blueBall: UInt32 = 0x1 << 1
static let edge: UInt32 = 0x1 << 2
static let all: UInt32 = UInt32.max
}
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
let redBall = SKSpriteNode(texture: SKTexture(imageNamed: "ball"), color: .red, size: CGSize(width: 40.0, height: 40.0))
redBall.colorBlendFactor = 1.0
redBall.position = CGPoint(x: frame.midX, y: frame.midY)
redBall.physicsBody = SKPhysicsBody(circleOfRadius: redBall.size.width/2)
redBall.physicsBody?.categoryBitMask = PhysicsCategory.redBall
redBall.physicsBody?.collisionBitMask = PhysicsCategory.all
redBall.physicsBody?.contactTestBitMask = PhysicsCategory.blueBall | PhysicsCategory.edge
//redBall.physicsBody?.velocity = CGVector(dx: 1.0, dy: 1.0)
//redBall.physicsBody?.applyImpulse(CGVector(dx: 1.0, dy: 1.0))
redBall.physicsBody?.applyForce(CGVector(dx: 1.0, dy: 1.0))
//redBall.physicsBody?.mass = 0.0
//redBall.physicsBody?.friction = 0.0
addChild(redBall)
let edgeRect = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
physicsBody = SKPhysicsBody(edgeLoopFrom: edgeRect)
physicsBody?.categoryBitMask = PhysicsCategory.edge
physicsBody?.collisionBitMask = PhysicsCategory.all
physicsBody?.contactTestBitMask = PhysicsCategory.redBall | PhysicsCategory.blueBall
setupPhysics()
}
func setupPhysics() {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
}
}