Here是我正在处理的问题的视频。正如你在视频中看到的那样,我移动一个灰色的球试图与红球碰撞。当两个物体发生碰撞时,没有发生弹跳,红球就会移动。我已经尝试过玩红球的密度,例如制作红球密度为0.00001。碰撞行为没有区别。
如何更改碰撞行为以便弹跳?
以下是灰球的属性:
func propertiesGrayBall() {
gray = SKShapeNode(circleOfRadius: frame.width / 10 )
gray.physicsBody = SKPhysicsBody(circleOfRadius: frame.width / 10 )
gray.physicsBody?.affectedByGravity = false
gray.physicsBody?.dynamic = true
gray.physicsBody?.allowsRotation = false
gray.physicsBody?.restitution = 1
}
以下是红球的属性:
func propertiesRedBall {
let redBall = SKShapeNode(circleOfRadius: self.size.width / 20
redBall.physicsBody = SKPhysicsBody(self.size.width / 20)
redBall.physicsBody?.affectedByGravity = false
redBall.physicsBody?.dynamic = true
redBall.physicsBody?.density = redBall.physicsBody!.density * 0.000001
redBall.physicsBody?.allowsRotation = false
redBall.physicsBody?.restitution = 1
}
以下是我如何移动灰球。
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if fingerIsOnGrayBall {
let touch = touches.first
var position = touch!.locationInView(self.view)
position = self.convertPointFromView(position)
grayBall.position = position
}
}
主要修改 球最初有附件。我删除它们以简化问题。这就是为什么评论可能不会与代码相加。
答案 0 :(得分:3)
如果通过设置其位置(直接或使用SKAction
)移动节点(使用物理主体),该节点将不会成为物理模拟的一部分。相反,您应该通过施加力/脉冲或设置其速度来移动节点。以下是如何执行此操作的示例:
首先,定义一个变量来存储触摸的位置
class GameScene: SKScene {
var point:CGPoint?
然后,从代码中删除以下语句
redBall.physicsBody?.density = redBall.physicsBody!.density * 0.000001
最后,添加以下触摸处理程序
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if (node.name == "RedBall") {
point = location
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
if point != nil {
point = location
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
point = nil
}
override func update(currentTime: CFTimeInterval) {
if let location = point {
let dx = location.x - redBall.position.x
let dy = location.y - redBall.position.y
let vector = CGVector(dx: dx*100, dy: dy*100)
redBall.physicsBody?.velocity = vector
}
}