I am currently working on an arcade app where the user taps for the sprite to jump over an obstacle and swipes down for it to slide under an obstacle. My problem is that when I begin a swipe the touchesBegan function is called so the sprite jumps instead of sliding. Is there a way to distinguish these two?
You can use a gestures state to fine tune user interaction. Gestures are coordinated, so shouldn't interfere with each other.
func handlePanFrom(recognizer: UIPanGestureRecognizer) {
if recognizer.state != .changed {
return
}
// Handle pan here
}
func handleTapFrom(recognizer: UITapGestureRecognizer) {
if recognizer.state != .ended {
return
}
// Handle tap here
}
How about using a slight delay for your touch controls? I have a game where I do something similar using a SKAction with delay. Optionally you can set a location property to give your self a bit of wiggle room with the touchesMoved method incase someone has a twitchy finger (thanks KnightOfDragon)
let jumpDelayKey = "JumpDelayKey"
var startingTouchLocation: CGPoint?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
// starting touch location
startingTouchLocation = location
// start jump delay
let action1 = SKAction.wait(forDuration: 0.05)
let action2 = SKAction.run(jump)
let sequence = SKAction.sequence([action1, action2])
run(sequence, withKey: jumpDelayKey)
}
}
func jump() {
// your jumping code
}
Just make sure the delay is not too long so that your controls dont feel unresponsive. Play around with the value for your desired result.
Than in your touches moved method you remove the SKAction if your move threshold has been reached
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
guard let startingTouchLocation = startingTouchLocation else { return }
// adjust this value of how much you want to move before continuing
let adjuster: CGFloat = 30
guard location.y < (startingTouchLocation.y - adjuster) ||
location.y > (startingTouchLocation.y + adjuster) ||
location.x < (startingTouchLocation.x - adjuster) ||
location.x > (startingTouchLocation.x + adjuster) else {
return }
// Remove jump action
removeAction(forKey: jumpDelayKey)
// your sliding code
}
}
You could play around with Gesture recognisers although I am not sure that will work and how it affects the responder chain.
Hope this helps
Related
I have a project where I’m adding three UILabels to the view controller’s view. When the user begins moving their finger around the screen, I want to be able to determine when they their finger is moving over any of these UILabels.
I’m assuming a UIPanGestureRecognizer is what I need (for when the user is moving their finger around the screen) but I’m not sure where to add the gesture. (I can add a tap gesture to a UILabel, but this isn’t what I need)
Assuming I add the UIPanGestureRecognizer to the main view, how would I go about accomplishing this?
if gesture.state == .changed {
// if finger moving over UILabelA…
// …do this
// else if finger moving over UILabelB…
// …do something else
}
You can do this with either a UIPanGestureRecognizer or by implementing touchesMoved(...) - which to use depends on what else you might be doing.
For pan gesture, add the recognizer to the view (NOT to the labels):
#objc func handlePan(_ g: UIPanGestureRecognizer) {
if g.state == .changed {
// get the location of the gesture
let loc = g.location(in: view)
// loop through each label to see if its frame contains the gesture point
theLabels.forEach { v in
if v.frame.contains(loc) {
print("Pan Gesture - we're panning over label:", v.text)
}
}
}
}
For using touches, no need to add a gesture recognizer:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let t = touches.first {
// get the location of the touch
let loc = t.location(in: view)
// loop through each label to see if its frame contains the touch point
theLabels.forEach { v in
if v.frame.contains(loc) {
print("Touch - we're dragging the touch over label:", v.text)
}
}
}
}
How can I avoid a UIButtons .touchDragEnter and .touchDragExit functions from rapid firing? This question demonstrates the issue perfectly, but the only answer does not describe how to work around it. I'm trying to animate a button when the users finger on the button, and animate it again when their finger slides off. Are there any better ways to do this? If not, how should I stop my animation code from firing multiple times when the users finger is right between an .enter and an .exit state?
You could instead track the location of the touch point itself and determine when the touch point moves in and out of the button
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
// moving in to the button
if button.frame.contains(point) && !wasInButton {
// trigger animation
wasInButton = true
}
// moving out of the button
if !button.frame.contains(point) && wasInButton {
// trigger animation
wasInButton = false
}
}
}
wasInButton could be a boolean variable set to true when there is a touch down in the button's frame:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = t.location(in: self)
if button.frame.contains(point) {
wasInButton = true
// trigger animation
} else {
wasInButton = false
}
}
This would require you to subclass the button's superview. And since you might not want to animate as soon as the point leaves the button's frame (because the user's finger or thumb would still be covering most of the button), you could instead do the hit test in a larger frame that encapsulates your button.
I am currently working at a sidescroller game, in which the jump height depends on how long the player presses the right half of the screen.
Everything works just fine, except if the user touches the screen quickly. This causes the jump to be as big as possible.
Am I doing something wrong or is this just a problem with the way SpriteKit works?
How can I solve this problem?
EDIT: Here are all the methods handling touches in my game:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
for touch in touches
{
swiped = false
let location = touch.location(in: cameraNode)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.065)
{
if self.swiped == false
{
if location.x < 0
{
self.changeColor()
}
else
{
self.jump()
}
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
for touch in touches {
let location = touch.location(in: cameraNode)
if location.x > 0
{
// Right
thePlayer.endJump()
}
}
}
And then there is also a gesture recognizer handling swiping left and right, with the following handlers:
#objc func swipedRight()
{
if walkstate != .walkingRight
{
walkstate = .walkingRight
}
else
{
boost(direction: 0)
}
swiped = true
}
#objc func swipedLeft()
{
if walkstate != .walkingLeft
{
walkstate = .walkingLeft
}
else
{
boost(direction: 1)
}
swiped = true
}
Hopefully this is enough to describe the problems. The code above is everything I am doing to handle touches.
Well, the problem was, that I am using a DispatchQueue command to call the jumping method after a short delay, in case the user swiped and not tapped. As a result the touchesEnded method gets called before the jump has even started and thus can not be stopped anymore.
To solve this problem I added a boolean variable which is set to true as soon as the player touches the screen and set to false whenever the users finger leaves the screen. In order to jump this variable has to be set to true and thereby the character will not jump after a quick touch anymore.
I've had a lot of success in the past using MGSwipeTableCell to swipe to dismiss cells, but my current task calls to swipe an entire section in the same behavior.
I currently have a swipe gesture recognizer in the UITableView, when the swipe gesture is triggered, I calculate the section the touch was recieved, and delete the objects that populate that section (in core data), then call the delete animation:
//Delete objects that populate table datasource
for notification in notifications {
notificationObject.deleted = true
}
DataBaseManager.sharedInstance.save()
let array = indexPathsToDelete
let indexSet = NSMutableIndexSet()
array.forEach(indexSet.add)
//Delete section with animation
self.notificationsTableView.deleteSections(indexSet as IndexSet, with: .left)
This works, but is not ideal. Ideally we would like the whole section to drag with your finger (and when released at a certain point, it goes off screen), similar to MGSwipeTableCell. What is the best way to approach this? Is there another library which allows swipe to delete sections (I can't find any)? Or is this something I will have to create myself.
I haven't tested this but the idea is below. Take a view (self.header) and use the touchesBegan... method to detect the user placing their finger on screen. Then, follow the finger with the touchesMoved... method and calculate the difference between the last offset and the next. It should grow by 1 (or more) depending on how fast the user is moving their finger. Use this value to subtract the origin.x of the cell's contentView.
var header: UIView!
var tableView:UITableView!
var offset:CGFloat = 0
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Touches Began. Disable user activity on UITableView
if let touch = touches.first {
// Get the point where the touch started
let point = touch.location(in: self.header)
offset = point.x
}
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
// Get the point where the touch is moving in header
let point = touch.location(in: self.header)
// Calculate the movement of finger
let x:CGFloat = offset - point.x
if x > 0 {
// Move cells by offset
moveCellsBy(x: x)
}
// Set new offset
offset = point.x
}
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// Reset offset when user lifts finter
offset = 0
}
func moveCellsBy(x: CGFloat) {
// Move each visible cell with the offset
for cell in self.tableView.visibleCells {
// Place in animation block for smoothness
UIView.animate(withDuration: 0.05, animations: {
cell.contentView.frame = CGRect(x: cell.contentView.frame.origin.x - x, y: cell.contentView.frame.origin.y, width: cell.contentView.frame.size.width, height: cell.contentView.frame.size.height)
})
}
}
Brandon's answer is correct, however, INSPullToRefresh library has issues when using touches began and other touch delegate methods.
What I had to do was implement a UIPanGestureRecognizer and track the touch when that gesture recognizer event is fired
So I am wondering about something. I have 3 functions:
func makeHeroRun(){
let heroRunAction = SKAction.animateWithTextures([ heroRun2, heroRun3, heroRun4, heroRun3], timePerFrame: 0.2)
let repeatedWalkAction = SKAction.repeatActionForever(heroRunAction)
hero.runAction(repeatedWalkAction)
}
func makeHeroJump(){
let heroJumpAction = SKAction.animateWithTextures([heroJump1, heroJump2, heroJump2], timePerFrame: 0.2)
hero.runAction(heroJumpAction)
}
func makeHeroSlide(){
let heroSlideAction = SKAction.animateWithTextures([heroSlide1, heroSlide2], timePerFrame: 0.1)
hero.runAction(heroSlideAction)
}
And also my touchesBegan:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var touch = touches.first as! UITouch
var point = touch.locationInView(self.view)
if point.x < size.width / 2 // Detect Left Side Screen Press
{
makeHeroSlide()
}
else
if point.x > size.width / 2 // Detect Right Side Screen Press
{
makeHeroJump()
}
}
"Hero" is the player running in the game.
What i want is that when the "makeHeroSlide" is finish running, i want to repeat "makeHeroRun", so after the hero has been sliding, it should continue to run. And when the hero is jumping, it should stop running, and when the hero hits the ground, it should continue to run again. How can i do this? I want sort of the same functions that are in the "Line Runner" game in AppStore where the player Jumps and Roll.
You can call runAction function with completion: as second parameter which you can use to specify block to execute after it finishes executing the action.
hero.runAction(heroSlideAction, completion: {() -> Void in
// do something here
})