我有一个项目,其中一个球在2个山丘之间滚动,我希望它永远滚动。使用样条曲线点来创建山丘(在(0,300),(375,0)和(750,300)处有3个点)。我已经确保球和地面的摩擦力和恢复力设置为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()
})
}
}
答案 0 :(得分:0)
SpriteKit中的物理学是现实生活的基本表示。 SpriteKit中的许多现实生活中的物理原理都是相同的。
您的球正消耗所有的动能来滚上一座小山。滚下山坡并没有给它足够的能量来滚过另一侧。最终,球将完全停止滚动,并停留在两个山丘之间的最低点。
当您的球触及一侧顶部的节点时,您的代码必须向球的CGVector添加足够的距离,以使其向下滚动并向上滚动至另一侧以触及另一节点以添加至球的CGVector球以使其在第一山丘上来回滚动以接触第一个节点并添加到球的CGVector等。这将创建一个永不耗尽能量的无限滚动球。