ScrollView in SpriteKit - ios

I have found a few other questions and answers similar to this, but none of them quite work perfect for me.
My vision is to have a horizontal scrollable view at the bottom of the screen where I can scroll through what will look like cards in a hand. Ideally, I could eventually make the card in the middle scaled up a bit and give it a highlighted look to show the user which card is selected. Even better would be if I could figure out how to keep the scroll view resizing to fir the number of sprites (cards) in the view.
Anyways, I am still very new to XCode and Swift, so it is hard for me to take what I find and change it. But, I am hoping to learn fast.
What I understand so far is that a UIScrollView could overlay the scene and with a moveable spritenode I could scroll through the view. The view would then translate the coordinates somehow to the SpriteKit Scene to move the sprites that will look like they are in the view. I think that's how it works. Any help would be great. I am pretty stuck. <3

You have to make your own logic that takes place in touchesMoved() using a global/member variable.
Unfortunately, a lot of gamedev and SK is math and logic.. You have to come up with your own problems and solutions.. There is no manual because the possibilities in programming and Swift are endless :)
Moving the cards:
Basically, you compare each touch location to the last one, and this becomes a "delta value" that you can use to perform actions.
Example, if I touch in the center of the screen, my touch location is 0,0 (or whatever your anchorpoint is set to). If I move my finger right, then I'm now at say 25, 0... This creates a "delta value" of +25x.
With that delta value, you can perform various actions such as moveBy for all the cards... so if I have a deltaX of +25, then I need to move all of the card nodes to the right (by a certain amount that you will determine according to your preferences). If I have a deltaX of -25, I move the cards to the left by a certain amount.
Where you do the actual moving is up to you--you could put a function in update() or touchesMoved() that constantly moves the cards a certain direction at a certain rate of that deltaX value..
Ok that was a mouthful... Maybe this will help:
for touch in touches {
myGlobalDeltaX = myDeltaXFunc(currentTouch: touch)
myMoveFunc(cards: allTheCards, byDeltaX: myGlobalDeltaX)
- You can search on how to make a Delta function, but it really is just the same thing from Algebra.
- myMoveFunc can be something as simple as iterating through all of your card nodes then running .moveBy on them at the same time.
Middle detection:
To detect which card is in the center, you would put in touchesEnded() or update() a call to check the name / identity of the node in the center of the screen... so something like
// `self` here refers to your GameScene class' instance, which is just an `SKScene` object
let centerX = self.frame.midX
let centerY = self.frame.midY
let center = CGPoint(x: centerX, y: centerY)
let centerNode = self.nodes(at: center)
You would obviously want to change centerX and centerY to wherever it is you want the middle card to be :) Right now, this is just in the dead-center of the screen.
Once you have a centerNode, you would then just need to do whatever function you have created to "select" it.
let selectedCard = centerNode
mySelectionFunc(middleCard: selectedCard)
This may look like a lot, but I drew out the steps to make understanding it a bit easier.. You can do all of this in one line if desired.
mySelectionFunc(middleCard: self.nodes(at: CGPoint(x: self.frame.x, y: self.frame.y)))
Hope this helps some!

Related

Swift - PanGesture Recognizer - move with object - speed of movement

I am using PanGesture Recognizer in Swift for iOS. Inside the action method, I am calling 3rd party method, that takes move direction and speed. From this, it calculates position of object:
objectPos += normalize(move) * speed
Problem is, that if I put my finger on a certain object and move with fingers, objects is not at the same position under my finger. It starts to move slower / faster. Moving directions are OK. Problem is with acceleration / decceleration - if I move faster, objects move faster.
In gesture callback I have tried:
let move = recognizer.translation(in: self.view);
let speed = sqrt((move.x * move.x) + (move.y * move.y));
and
let move = recognizer.velocity(in: self.view);
let speed = dt * sqrt((move.x * move.x) + (move.y * move.y));
Usually dt = 1.0 / 60.0. It is the gesture callback refresh rate (in code, I am calculating dt manually using difference of CFAbsoluteTimeGetCurrent()). Without this, If I use velocity directly to calculate speed, movement is too fast.
I have tried to calculate difference manually by subtracting current and last position, but still no luck.
I have also tried to "change speed" accoring to current view width and height, but none ot if worked. I am probably missing something, but dont know what.
It would be easier if you just computed the moves of the object based on acceleration when the user stops touching the object.
As long as the user has their finger on the object, it is much easier to just set the position of the object to the position you get from the pan gesture recognizer.
Ok... I have found the problem. Movement of th eobject it in screen normalized coordinates with corners [0,0] - [1,1]. So movement in Y axis (height) was correct, but in X axis (width) the speed was about half.
Multiply move.x with correct aspect ratio solved the problem. Basically, the moevement in X axis is enlarged manually.

Snake game movement issue Spritekit

I am trying to create a basic snake game using Swift and Spritekit. I have a sprite moving on the screen and when i swipe it starts moving in the swipe direction. I do this in the update method where I change the position of the sprite based on the swipe direction, a set speed and a fixed duration.
e.g. direction.x * blockMovePerSecond * CGFloat(actionDuration)
I have the sprites following each other, however, as soon as i swipe and the first sprite changes direction, the one following it moves diagonally instead of first on the x-axis and then the y-axis like a normal snakes game.
I tried the following options:
Tried keeping the distance that the sprite moves on each update equal
to the distance between the two sprites. However, the sprite runs off
the screen when i do that.
Made the first sprite create a path for the rest of the sprites to follow. However, the second sprite
runs off the screen and never shows up again. I think the problem is
because the path is open.
Here's my move method code for the sprites following the first sprite (snake head):
{
var temp:NSValue = lastNodeLocation // the lastnodelocation is from first sprite location
var tempNodeDirection = lastNodeDirection
let actionDuration = 1.0
let distanceToMoveThisFrame = tempNodeDirection.CGPointValue() * blockMovePerSecond * CGFloat(actionDuration)
var currentPosition = NSValue(CGPoint: blocksOfAlphabets[i].position)
let beforeDistance = CGPoint(x: temp.CGPointValue().x - currentPosition.CGPointValue().x, y: temp.CGPointValue().y - currentPosition.CGPointValue().y)
lastNodeLocation = NSValue(CGPoint: blocksOfAlphabets[i].position)
// move node to new location
var moveAction = SKAction.moveTo(temp.CGPointValue(), duration: 1.0)
node.runAction(moveAction)
}
Can somebody please help?
Thanks
Shuchi
Well your problem is that the runAction-methods don't wait to complete. So if you call another runAction-method while a sprite is already running an action, the new action will be started immediately.
You can work with sequences to finish the x-axis first: SKAction:sequence
I think the easiest thing to do here is to keep an array of snake sprite components (let's call these sprites a "Rib").
Every 5 seconds add a new Rib to the end of the array to make the snake grow.
Then, each half second in the update() method (or however long you want it to be):
check for any swipes that have happened since the last update and change direction of the first rib (the snake head) in the direction of the swipe.
now run through the snake array in reverse and set the location of node (n) to the node position of node (n-1).
There are other ways you could do it but I think this would be the easiest.

How to check if bottom of a SKSpriteNode is inside the current visible scene

I've been looking at Figure 7-3 in this sprite kit documentation: https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Actions/Actions.html but it has left me pretty confused. They seem to give the same name to multiple things e.g., camera/character.
I am in the default SKScene, MyScene class. In initWithSize, I create a SKNode *myWorld, just like the documentation suggests. I then have a series of methods that add my background images to myWorld. Scrolling that works just fine, but what I want to do is stop the vertical scrolling when the bottom of the images in myWorld reach the bottom of the scene. For the life of me, I cannot figure out how to refer to the bottom of myWorld. For the bottom of the scene, I simply do
CGPoint sceneFarBottomSide = CGPointMake(0, -self.size.height/2);
where self.anhorPoint is set to [0.5, 0.5].
How do I refer to the bottom of myWorld?
The edge of myWorld is whatever you set it to be. In other words, myWorld is a node which isn't itself a view or a sprite. It's simply an object that contains sprite or shape children (for example, SKSpriteNodes or SKShapeNodes). When you are adding your sprites to myWorld, keep track of their position. Then use their position to define the "size" of myWorld. You can use this size information along with myWorld.position to know when the (bottom) edge of myWorld is coming up.
It ended up being extraordinarily easy to resolve. Thanks Andrey for pointing me to that Apple documentation on the Adventure game, that's what really tipped me off and cleared up some of my understanding. Here's the few lines of code to get the behavior I desired:
// Move world
if (monkeyPosition.y > 0 && monkeyPosition.x > 0) {
[myWorld setPosition:CGPointMake(-monkeyPosition.x, -monkeyPosition.y)];
} else if (monkeyPosition.y > 0 && monkeyPosition.x < 0) {
[myWorld setPosition:CGPointMake(0, -monkeyPosition.y)];
}

Make Physics node move horizontal without spinning

Hello in a game I'm making using lua in Marmalade Quick,I have run into a problem with the physics.
I have a normal downward y gravity and have some notes that is affected by that.
Now I want to add some objects that "fly" horizontally on the X axis but I can not get it to work.
so one of the notes looks like this:
sky2 = director:createSprite(dw, 40, "textures/tractor.png")
physics:addNode(sky2, {type="dynamic"})
sky2.physics:setGravityScale(0)
my first thought was to
just add the following to an update listener
if(gameplaying == true) then
sky2.x = sky2.x-2.5
unfortunately this does not work after the node has got added physics
then I was looking into using
sky2.physics:applyapplyLinearImpulse or sky2.physics:applyForce
I used it like this
sky2.physics:applyapplyLinearImpulse(-10, 0, -20, 40)
The problem here is that the node then correctly moves along the axis but it is spinnig around (torque effects)..
Is there away to stop this or what am I doing wrong,,
thanks..
Found out that the Marmalade Quick Documentation was wrong, and to not input both a px and a px value but just 0 so sky2.physics:applyapplyLinearImpulse(-10, 0) this will apply the impulse at the centre of mass and make it move straight.

iOS: Draggable UIView (vertically only)

In my app I have a small subview that I'd like to tether in the bottom right corner and allow to be moved only vertically for a fixed distance.
I have some code to allow it to be dragged, but no further constraints:
- (void)viewDragged:(UIPanGestureRecognizer *)gesture
{
CGPoint translation = [gesture translationInView:keyView];
// move view
keyView.center = CGPointMake(keyView.center.x + translation.x,
keyView.center.y + translation.y);
// reset translation
[gesture setTranslation:CGPointZero inView:keyView];
}
I've looked around on StackOverflow and tried a couple of ways, but the only one that worked didn't take into account diagonal movement, and I couldn't find anything in regards to tethering it to one spot.
So does anyone know how this can be done? Many thanks
EDIT: Also, does anyone know of a good, informative reference doc (other than the Apple one) for topics of this nature?
can you just add in a line to the view dragged code that says if keyview.centre.y is less than some threshold (where you want it to stop), then don't change it below that. eg.
keyView.centre = CGPointMake(keyView.center.x,
keyView.center.y - translation.y < threshold ? threshold : keyView.center.y);
also remove the change to the x parameter to stop it moving diagonally.

Resources