【发布时间】:2018-10-14 20:12:14
【问题描述】:
我有一个项目,其中一个球在 2 个山丘之间滚动,我希望它永远滚动。山丘是使用样条点制作的(有 3 个点,在 (0,300)、(375,0) 和 (750,300) 处)。我已经确保球和地面的摩擦力和恢复力设置为 0,但它仍然来回滚动,上山的次数比上次少。
这是山丘和球的样子: Image
编辑:我被要求添加一些代码,所以这是我的 GameScene.swift 文件:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var ball = SKShapeNode()
func createView(){
removeAllActions()
removeAllChildren()
ball = SKShapeNode(circleOfRadius: 20)
ball.position = CGPoint(x:0, y:350)
ball.physicsBody = SKPhysicsBody(circleOfRadius: 20)
ball.physicsBody?.restitution = 0
ball.physicsBody?.friction = 0
ball.physicsBody?.mass = 0.1
ball.physicsBody?.linearDamping = 0
ball.physicsBody?.angularDamping = 0
ball.physicsBody?.isDynamic = true
ball.fillColor = .red
addChild(ball)
ball.physicsBody?.velocity = CGVector(dx: 0, dy: -400)
ball.physicsBody?.allowsRotation = true
self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)
var splinepoints = [CGPoint(x: 0 , y: 0),
CGPoint(x: 0, y: 300),
CGPoint(x: 375, y: 0),
CGPoint(x: 750, y: 300)]
let ground = SKShapeNode(splinePoints: &splinepoints, count: splinepoints.count)
ground.physicsBody = SKPhysicsBody(edgeChainFrom: ground.path!)
ground.physicsBody?.restitution = 0.0
ground.physicsBody?.friction = 0.0
addChild(ground)
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 0
self.physicsBody = border
}
override func didMove(to view: SKView) {
createView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
ball.physicsBody?.friction = 0
ball.physicsBody?.restitution = 0
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: {
})
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5), execute: {
self.createView()
})
}
}
【问题讨论】:
-
你能发布一些代码吗?我需要查看球物理和山物理的代码。
-
SpriteKit 物理是对现实生活的相当不错的模拟。球滚上山坡并消耗一些动能(CGVector)。然后,它正在获得其中的一部分,而不是全部,并在另一边回滚。消耗后并没有获得所有能量。当球到达一侧的顶部时,您的代码必须向球添加足够的能量才能将其向下和向上移动到另一侧。
标签: swift xcode sprite-kit game-physics skphysicsbody