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.
Related
I created a door with ARKit and I want create a scale animation. My goal is to scale it only along the y-axis (stretch the door to be longer).
I want the door to grow within a duration of 1 second.
My approach was to simply scale it but I only have options that allow me to scale my entire object along all 3 axis.
Next I tried node.scale = SCNVector3(0, 2, 0) and that works ok, but it has no nice animation to it. When I create a SCNAction() and run the code as a block with duration time, it still just changes the size without any smooth animation.
You need to use SCNTransaction. The simplest way to animate your node scaling would be something like this:
SCNTransaction.begin()
SCNTransaction.animationDuration = 3
node.scale = SCNVector3(0, 2, 0)
SCNTransaction.commit()
You might also need to modify pivot property of the node to position the animation correctly.
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.
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!
I created a rope based off this tutorial, except my rope has one ball attached on each end of the rope.
High Level: This is how they create the rope.
create an array of SKNodes
append each rope segment (node) to the array
add each node to the screen
join each node together to form a rope
(Then I add a ball on each end of the rope)
In my program I move the ball around and basically swing the rope around kind of like a stretchy pendulum.
Here's my issue: If I swing the rope around very hard, the rope stretches too much! How can I decrease the amount the rope stretches? I don't see a method to decrease the elasticity of the body.
If there is any other information that will be useful please let me know! Thanks in advance
You can try these two methods. The first method is to increase the property frictionTorque of SKPhysicsJointPin class.
The range of values is from 0.0 to 1.0. The default value is 0.0. If a
value greater than the default is specified, friction is applied to
reduce the object’s angular velocity around the pin.
An example for the tutorial you followed, before adding a joint to the scene, modify frictionTorque:
for i in 1...length {
let nodeA = ropeSegments[i - 1]
let nodeB = ropeSegments[i]
let joint = SKPhysicsJointPin.jointWithBodyA(nodeA.physicsBody!, bodyB: nodeB.physicsBody!,
anchor: CGPointMake(CGRectGetMidX(nodeA.frame), CGRectGetMinY(nodeA.frame)))
joint.frictionTorque = 0.5 // Add this line
scene.physicsWorld.addJoint(joint)
}
The second method is to limit the swing angle of the pin joint. After enabling shouldEnableLimits, adjust lowerAngleLimit and upperAngleLimit in radians.
Read more about SKPhysicsJointPin Class Reference for Determining the Characteristics of the Pin Joint.
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)];
}