我一直在学习SpriteKit(使用Ray Wenderlich等人的教程中的iOS游戏)来创建基于Breakout的我自己的非常简单的测试游戏,以查看我是否可以应用我学到的概念。我决定通过使用.sks文件来创建精灵节点并替换我的手动边界检查和碰撞与物理实体来简化我的代码。但是,我的球在与陡峭的角度相撞时会与墙壁/其他矩形保持平行(如在上下滑动)。下面是相关的代码 - 我提出的物理性质身体成代码以使它们更明显:Swift中的SpriteKit物理效果 - 球滑过墙而不是反射
import SpriteKit
struct PhysicsCategory {
static let None: UInt32 = 0 // 0
static let Edge: UInt32 = 0b1 // 1
static let Paddle: UInt32 = 0b10 // 2
static let Ball: UInt32 = 0b100 // 4
}
var paddle: SKSpriteNode!
var ball: SKSpriteNode!
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVector.zeroVector
let edge = SKNode()
edge.physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)
edge.physicsBody!.usesPreciseCollisionDetection = true
edge.physicsBody!.categoryBitMask = PhysicsCategory.Edge
edge.physicsBody!.friction = 0
edge.physicsBody!.restitution = 1
edge.physicsBody!.angularDamping = 0
edge.physicsBody!.linearDamping = 0
edge.physicsBody!.dynamic = false
addChild(edge)
ball = childNodeWithName("ball") as SKSpriteNode
ball.physicsBody = SKPhysicsBody(rectangleOfSize: ball.size))
ball.physicsBody!.usesPreciseCollisionDetection = true
ball.physicsBody!.categoryBitMask = PhysicsCategory.Ball
ball.physicsBody!.collisionBitMask = PhysicsCategory.Edge | PhysicsCategory.Paddle
ball.physicsBody!.allowsRotation = false
ball.physicsBody!.friction = 0
ball.physicsBody!.restitution = 1
ball.physicsBody!.angularDamping = 0
ball.physicsBody!.linearDamping = 0
physicsWorld.contactDelegate = self
}
忘记之前提到这一点,但我添加了一个简单的touchesBegan功能调试反弹 - 它只是调整
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let moveToward = touch.locationInNode(self)
let targetVector = (moveToward - ball.position).normalized() * 300.0
ball.physicsBody!.velocity = CGVector(point: targetVector)
}
归一化()函数只是降低了球/触摸位置增量为单位矢量,并且在减去操作,其允许CGPoint减法的控制装置:所述速度在触摸点指向球。
球/边缘碰撞应始终以恰好相反的角度反射球但由于某种原因,球真的似乎有一个正确的角度。我当然可以实施一些解决方法来手动反映球的角度,但重点是我想要使用SpriteKit中内置的物理功能来完成这一切。有什么明显的我失踪了?
您将需要移动精灵向其物理体施加力量或冲动或通过设定其速度属性。如果您通过动作或直接设置其位置,精灵将不参与物理模拟。 – 0x141E 2014-12-27 22:10:40
对不起,我遗漏了我的速度调整。我只是编辑它,但基本上它是一个触摸事件,它将球速度设置为SKScene中的触摸点。 – 2014-12-28 20:15:51
您是否在接触发生时轻敲并松开手指或将其按住? – 0x141E 2014-12-29 06:25:56