Thursday, February 14, 2019

ios - How can I avoid a delay with continues touch detection in swift?


I want control a character on my screen with a continuous swipe gesture. As soon as I do a swipe +x or -x my character moves left or right. And as long as I hold my finger it continuous to move to the direction in that I swiped. When I swipe into the opposite direction of my last swipe without leaving my finger from the touch ground, my character should move into this direction. When I release my finger from the touch screen, my character should stops instantly.


My problem is that there is often a small delay within the change of direction. And this delay makes it less precise.


override func touchesBegan(touches: Set, withEvent event: UIEvent) {
/* Called when a touch begins */
var player = self.childNodeWithName("man")

for touch in (touches as! Set) {
let location = touch.locationInNode(self)

let touchedNode = self.nodeAtPoint(location)

lastFingerPosition = location

}
}

override func touchesMoved(touches: Set, withEvent event: UIEvent){
var player = self.childNodeWithName("man")


for touch in (touches as! Set) {
let location = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)

if(location.x > lastFingerPosition?.x && lastMoveDirection != "right"){
movePlayer("right")
} else if(location.x < lastFingerPosition?.x && lastMoveDirection != "left"){
movePlayer("left")
}
}

}

//@Todo: Wenn man touchMoved und nicht über dem Button hoch geht, wird die Action nicht aufgehoben
override func touchesEnded(touches: Set, withEvent event: UIEvent) {
var player = self.childNodeWithName("man")

for touch in (touches as! Set) {
let location = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)


player?.removeAllActions()
lastMoveDirection = ""
}
}

func movePlayer(direction: String) {
var player = self.childNodeWithName("man")

if(lastMoveDirection != direction){
player?.removeAllActions()

lastMoveDirection = direction

var duration:CGFloat? = 0
var x = player?.position.x
duration = x!

if(direction == "left"){
var xDestination:CGFloat = 10
var run = SKAction.moveToX(10, duration: NSTimeInterval(Double(duration! / runSpeed)))
player?.runAction(run, withKey: "moveLeft")

} else if(direction == "right") {
duration = self.frame.width - x!
var xDestination = frame.size.width - 1
var run = SKAction.moveToX(xDestination, duration: NSTimeInterval(Double(duration! / runSpeed)))
player?.runAction(run, withKey: "moveRight")
}
}
}


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...