【发布时间】:2020-02-01 14:55:04
【问题描述】:
我有一个SKSpriteNode 作为一个球,它被赋予了所有SKPhysicsBody 属性在各个方向移动。我现在想要的是让它unidirectional (只朝它之前没有移动过的方向移动,而不是回到它曾经移动过的路径)。目前我对这个问题有以下想法,
- 创建一个
fieldBitMask,到被它迭代的路径并排斥 球不回去 - 通过
touchesBegan/ touchesMoved方法在球上应用某种force/ impulses以防止它返回 - 可以在
update方法中处理的东西 - 来自 stackflowoverflow 的救星,他甚至在周末都在编码 :)
支持代码 sn-ps 以便更好地理解,
//getting current touch position by using UIEvent methods
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
//ball created
func createPlayer(){
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 220, y: 420)
player.zPosition = 1
//physics for ball
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.allowsRotation = false
player.physicsBody?.linearDamping = 0.5
player.physicsBody?.categoryBitMask = collisionTypes.player.rawValue
player.physicsBody?.contactTestBitMask = collisionTypes.finish.rawValue
player.physicsBody?.collisionBitMask = collisionTypes.wall.rawValue
addChild(player)
}
//unwarp the optional property, calclulate the postion between player touch and current ball position
override func update(_ currentTime: TimeInterval) {
guard isGameOver == false else { return }
if let lastTouchPosition = lastTouchPoint {
//this usually gives a large value (related to screen size of the device) so /100 to normalize it
let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x/100, dy: diff.y/100)
}
}
【问题讨论】:
-
我明天要提交这个,感谢您的帮助;(
标签: ios swift sprite-kit skspritenode skphysicsbody