我正在使用spritekit开发一个相对简单的儿童游戏,就像一个虚拟玩具屋。在这个游戏中他们是纸质角色,但也有一些互动对象,如弹力球。目前,我能够在移动手指时给出球的速度,并且球与我的移动手指保持一致。然而,当我将手指(拿着球)保持在屏幕上的一个位置时,球变得不稳定并且开始跳到整个房间或从我的手指中掉出来。我通过将isDynamic设置为false来解决这个问题,同时保持它们并将其位置更新到我的手指,但这不能用于球,因为它会阻止速度工作。我已经包含了moveChar和moveBall函数,因此你可以看到它们的区别,以及touchesMoved它们被调用的位置。谢谢!
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// print("Ball velocity is: ", ball.physicsBody?.velocity as Any)
if let touch = touches.first {
let location = touch.location(in: self)
let startLocation = touch.previousLocation(in: self)
if let sprite = currentSpriteHeld {
if sprite == ball {
moveBall(sprite: sprite, to: location)
} else {
moveChar(sprite: sprite, to: location)
}
} else {
let impulse = CGFloat(2.0)
let dx = (impulse * (startLocation.x - location.x))
let dy = (impulse * (startLocation.y - location.y))
let cameraPos = desiredPosition;
let newCameraPos = CGPoint(x: cameraPos.x+dx, y: cameraPos.y + dy);
// cameraNode.position = newCameraPos
desiredPosition = newCameraPos
}
}
}
func moveBall(sprite: SKSpriteNode, to location: CGPoint) {
ball.physicsBody?.velocity = CGVector(dx: 0.0, dy: 0.0)
let distance = CGDistance(from: sprite.position, to: location);
print("CGDistance is: ", distance)
if distance > 10.0 {
let dx = location.x-sprite.position.x;
let dy = location.y-sprite.position.y;
let drag:CGFloat = 0.01
var vel = CGVector(dx: dx/drag, dy: dy/drag)
vel = velocityCheck(vel: vel);
sprite.physicsBody!.velocity = vel
} else {
ball.position = location;
}
}
func moveChar(sprite: SKSpriteNode, to location: CGPoint) {
if (sprite == dad) {
dad.texture = dadPickup
}
sprite.physicsBody?.isDynamic = false;
sprite.zPosition = 2;
sprite.position = location
touchPoint = location;
}
解决:我通过将moveBall移动到触摸结束来修复此问题。现在我可以像握住精灵一样握住球,并且只有当我放手时才施加速度(导致震动)。
答案 0 :(得分:0)
解决:我通过将moveBall移动到触摸结束来修复此问题。现在我可以像握住精灵一样握住球,并且只有当我放手时才施加速度(导致震动)。