好的,目前在我的游戏中,我可以拖动,滑动和轻弹节点。但是,我希望用户只能滑动/轻弹节点,我不希望用户能够拖动节点。我怎么能这样做?
这是我目前的代码:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if ball.frame.contains(location) {
touchPoint = location
touching = true
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first as UITouch!
let location = touch!.location(in: self)
touchPoint = location
for touch in touches {
let location = touch.location(in: self)
touchPoint = location
if touching {
if touchPoint != ball.position {
let dt:CGFloat = 1.0/60.0
let distance = CGVector(dx: touchPoint.x-ball.position.x, dy: touchPoint.y-ball.position.y)
let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
ball.physicsBody!.velocity=velocity
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touching = false
for touch in touches {
let location = touch.location(in: self)
touchPoint = location
let node = self.atPoint(location)
}
}
答案 0 :(得分:1)
这就是UIGestureRecognizers
存在的原因。在您的视图上添加UIPanGestureRecognizer
,并使用velocity(in:UIView)
方法让您知道轻弹的方向和速度。
请注意,您不能在节点上放置手势,只能在视图中放置手势,因此如果您只使用手势,则需要从视图坐标转换为场景坐标。
您还可以让手势的触摸向下流入场景,允许正常的触摸调用,并使用平移手势的速度。
https://developer.apple.com/reference/uikit/uipangesturerecognizer