基本上,我想使用自定义手势制作手机游戏。手势有点像从左到右以及从右到左摩擦屏幕。
如果手势从左向右移动,则将调用方法并添加一个点。而且,一旦手势从右向左摩擦,用户也可以获得一分。
但是问题是,当我使用滑动手势识别器时,必须从屏幕上松开手指才能调用该方法。如果我只是做摩擦手势,则无法调用该方法来添加点。
相反,我尝试使用touchesBegan,touchesMoved方法来检测手指的位置。但是,touchesMoved将创建许多要与起点进行比较的点,这导致多次调用该方法,而不是一次。
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches
{
self.touchStartPoint = touch.locationInView(self.myView).x
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches
{
self.touchOffsetPoint = touch.locationInView(self.myView).x - touchStartPoint
if tempTouchOffsetPoint < touchOffsetPoint
{
var xValueIncreaseArray: NSMutableArray = []
xValueIncreaseArray.addObject(touchOffsetPoint)
var maxValue: Double = (xValueIncreaseArray as AnyObject).valueForKeyPath("@max.self") as Double
println("\(maxValue)")
if maxValue - Double (self.touchStartPoint) > 50
{
println("right")
}
println("right")
}
else if tempTouchOffsetPoint > touchOffsetPoint
{
/* var xValueDecreaseArray: NSMutableArray = []
xValueDecreaseArray.addObject(touchOffsetPoint)*/
println("left")
}
else if tempTouchOffsetPoint == touchOffsetPoint
{
println("Remain")
}
tempTouchOffsetPoint = touchOffsetPoint
}
有什么方法可以检测到摩擦手势吗?而且,每当手指旋转方向时,它将仅调用一次方法来向用户添加分数?非常感谢!
最佳答案
这对我有用:
let deadZone:CGFloat = 10.0
var previousTouchPoint: CGFloat!
var isMovingLeft:Bool? = nil
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let point = touches.anyObject()?.locationInView(self)
if let newPoint = point?.x {
if previousTouchPoint == nil {
println("Started")
previousTouchPoint = newPoint
} else {
// Check if they have moved beyond the dead zone
if (newPoint < (previousTouchPoint - deadZone)) || (newPoint > (previousTouchPoint + deadZone)) {
let newDirectionIsLeft = newPoint < previousTouchPoint
// Check if the direction has changed
if isMovingLeft != nil && newDirectionIsLeft != isMovingLeft! {
println("Direction Changed: Point")
}
println((newDirectionIsLeft) ? "Moving Left" : "Moving Right")
isMovingLeft = newDirectionIsLeft
previousTouchPoint = newPoint
}
}
}
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
previousTouchPoint = nil
isMovingLeft = nil
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
previousTouchPoint = nil
isMovingLeft = nil
}
关于ios - 在iOS中进行摩擦屏幕手势?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26204644/