Rotate Sprite on touch swift 3 IOS - ios

I am trying to replicate the flappy bird game as a practise.
When playing flappy bird when you touched the screen the bird tilted upwards slightly (and went up) then when you released he would kind of rotate downwards and drop.
I have all the physics set up I just need to know how to rotate the bird up (whilst keeping the flappy wing animation) and then rotate him to face down again when you let go.
Easy I'm sure?...

In update frames method put
-Swift 3-
let value = Bird.physicsBody!.velocity.dy * ( Bird.physicsBody!.velocity.dy < 0 ? 0.005 : 0.001 )
Bird.zRotation = min( max(-0.5 //determines how much rotation when falling down, value), 1 //determines how much when jumping up )
bird will rotate whenever impulse is applied

Without knowing SpriteKit I would consider rotating your coordinate system as in the second answer to this question. #ToddFincannon proposes to save the graphics state, translate/rotate your coordinate system (most probably to the center of your sprite), draw and restore. Roughly copying his answer that will translate into
let c = UIGraphicsGetCurrentContext()!
c.saveGState()
c.translateBy(x: sprite.midX, y: midY)
c.rotate(by: angle * .pi / 180)
// Draw your sprite at 0, 0 (it is already translated)
c.restoreGState()
In order to be rotated upwards you will likely need a negative angle.

Related

Jumping with Sprite Kit and Swift

I am creating an app in Sprite Kit and Swift and want to create a sprite that jumps upwards while the screen is pressed, therefore jumping higher as the screen is pressed higher. I have achieved that effect, but gravity in the physics engine is not being applied until after the screen is released. Therefore the jumps are infinite (increasing exponentially) rather than levelling off at a certain point (like a quadratic equation / parabola).
How does one apply gravity actively during the motion of a sprite?
Here is my basic movement code:
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
// touched is true while screen is touched
if touched {
nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -5, dy: 0))
}
}
NOTE: The object is jumping right and left rather than up and down
The gravity should be working constantly, and probably is. As you apply an impulse on every tick however, this force is much stronger than the gravity.
What you need to do is to decrease the effect of the impulse over time.
This can be achieved in a number of ways, for instance by using the position of the sprite as a base for the impulse: The higher the sprite position, the lower the impulse.
if touched {
let minX: CGFloat = 200 // some suitable value
let multiplier: CGFloat = 10
let force = max(0, (nodeLeft.position.x / minX - 1) * multiplier)
nodeLeft.physicsBody?.applyImpulse(CGVector(dx: -force, dy: 0))
}
The minX value in the above example probably makes no sense. But the logic is fairly sound I believe. You obviously need to experiment and tweak this (and the multiplier) to suit your needs.

infinite scrolling background - how to make objects move with ground

I have an infinitely scrolling background and a character 'walking' on the ground plane.
I want to drop objects from above and have them land on the ground - so far so good. But the objects don't move with the ground.
Can't find any examples where this is taken care of.
my 'ground' is just an edge at the correct height with regard to my graphics background.
let Edge = SKNode()
Edge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero, toPoint: CGPointMake(self.frame.width + 1, 0))
Edge.position = CGPointMake(0, bottomShelf_ItemStartPosition.y)
self.addChild(Edge)
I've tried giving my ground SKSriteNode physical properties, but this didn't make any difference.
What would be the best approach for this? Must be a simple way to make the moving ground effect objects.
adding scroll routine:
func backgroudScrollUpdate1(){
back.position = CGPoint(x: back.position.x - scrollPerFrameAmount, y: back.position.y)
back2.position = CGPoint(x: back2.position.x - scrollPerFrameAmount, y: back2.position.y)
if (back.position.x < -(back.size.width / 2)) {
back.position = CGPointMake(back2.position.x + back.size.width, back.position.y)
}
if (back2.position.x < -(back.size.width / 2)) {
back2.position = CGPointMake(back.position.x + back2.size.width, back2.position.y)
}
}
update - some progress
i have set up a physics world, where my ground is infinitely scrolling. I've got some items that fall out of the 'sky' and land on the ground. I can move the things around by applying impulse directly or one thing hitting another.
But, what i expected is that the scrolling ground would 'pull' things along with it if they are on the ground?
I have played around with different friction levels of both the ground at the items touching the ground, but it doesn't seem to matter.
one thing that did sort of work is if i set the phsyics body of an item to a circle, then the ground does influence the item, turning it around in the opposite direction of the scrolling - but when it hits an edge it just stops, rather than spinning at the edge.
If that part is working, then why wouldn't a rectangle be dragged along by the ground ?
would love to see example code of a phsyics world that does have the ground effecting other nodes..

Keeping Direction of a Vector Constant while Rotating Sprite

I'm trying to make a game where the sprite will always move to the right when hit by an object. However since the Sprite rotates constantly and the zero radians rotates with the Sprite causes my calculated magnitude to go the opposite direction if the sprite is facing left and hits the object. Is there a way to keep the direction of the magnitude always pointing to the right even if the zero is facing left?
// referencePoint = upper right corner of the frame
let rightTriangleFinalPoint:CGPoint = CGPoint(x: referencePoint.x, y: theSprite.position.y)
let theSpriteToReferenceDistance = distanceBetweenCGPoints(theSprite.position, b: referencePoint)
let theSpriteToFinalPointDistance = distanceBetweenCGPoints(theSprite.position, b: rightTriangleFinalPoint)
let arcCosineValue = theSpriteToFinalPointDistance / theSpriteToReferenceDistance
let angle = Double(acos(arcCosineValue))
let xMagnitude = magnitude * cos(angle)
let yMagnitude = (magnitude * sin(angle)) / 1.5
Not sure if this works for you:
I would use an orientation constraint to rotate the sprite. The movement can be done independent from the orientation in that case.
I made an tutorial some time ago: http://stefansdevplayground.blogspot.de/2014/09/howto-implement-targeting-or-follow.html
So I figured out what was going on.
It seems like the angle doesn't rotate with the Sprite like I originally thought and the vector that I am making is working with the code above. THE problem that I had was that I also set the collision bit for the objects which is wrong. If I only set the contact bit for the objects against the sprite the my desired outcome comes true.

How to make a node to rotate around a point outside of the node in a spritekit game project

I came across this answer, but the answer is not clear to me. Can someone provide some sample code?
Create an SKNode and set its position to the center of rotation. Add the node that should rotate around that center as child to the center node. Set the child node's position to the desired offset (ie radius, say x + 100). Change the rotation property of the center node to make the child node(s) rotate around the center point.
Specifically, "Change the rotation property of the center node" to what?
var centerNode: SKSpriteNode = SKSpriteNode(imageNamed: "image1")
centerNode.position = CGPointMake(self.frame.width/2, self.frame.height/2)
self.addChild(centerNode)
var nodeRotateMe: SKSpriteNode = SKSpriteNode(imageNamged: "image2")
nodeRotateMe.position = CGPointMake(self.frame.width/2 + 100, self.frame.height/2 + 100)
centerNode.addChild(nodeRotateMe)
// Change the rotation property of the center node to what??
centerNode.zRotation = ?
You have a couple of options:
1) You could rotate the centerNode over time in your SKScene's update: method by changing its zRotation property manually. You'll have to change the value slowly, at every call to update: to achieve a gradual rotation.
Note that the zRotation property is in radians, with means a 180 degree rotation would be equal to pi (M_PI). SKScene strives to update: at 60 FPS, which means to rotate 360 degrees over 5 seconds, you'd need to increment by 1/300th of a degree every call to update, which would be 1/150th of pi every update.
centerNode.zRotation = centerNode.zRotation + CGFloat(1.0/150.0 * M_PI)
Of course, there is no guarantee that your scene will be able to update at 60 FPS, so you may have to monitor the currentTime variable in update: and adjust accordingly.
2) Probably better, you could use an SKAction to rotate the centerNode for you.
let rotateAction = SKAction.rotateByAngle(CGFloat(2 * M_PI), duration: 5.0)
centerNode.runAction(rotateAction)
Note that the rotation angle is in radians, not degrees. Also note that the centerNode need not be a Sprite Node if you don't want to display an image there; it could be a regular SKNode.

Moving layer causes physics object to stay in place

I'm fiddling around with cocos2d v3 in combination with sprite builder.
The game is a simple catch and avoid game, objects coming down an the hero is standing in the bottom of the screen and you can move him around with the accelerometer.
I have a level file (cclayer) with some objects (ccnode) in it, the have physics enabled.
In my update function I move the layer slowly down.
If the objects have physics enabled, they just drop down. If I switch it to statics physics, they stay in place.
The only way I can find to move the object along with the layer is to turn off the physics completely. But then the collisions won't work anymore...
This kept me buys for the past 4 hours or so.
What is the best approach for this situation?
Thanks in advance guys!
this is my update function:
- (void)update:(CCTime)delta {
float maxX = winSize.width - _hero.contentSize.width/2;
float minX = _hero.contentSize.width/2;
CMAccelerometerData *accelerometerData = _motionManager.accelerometerData;
CMAcceleration acceleration = accelerometerData.acceleration;
CGFloat newXPosition = _hero.position.x + acceleration.x * 1000 * delta;
newXPosition = clampf(newXPosition, minX, maxX);
_hero.position = CGPointMake(newXPosition, _hero.position.y);
//level position
CGPoint oldLayerPosition = _levelNode.position;
float xNew = oldLayerPosition.x;
float yNew = oldLayerPosition.y -1.4f;
_levelNode.position = ccp(xNew, yNew);
}
This is a design decision made within the physics engine. Physics bodies do not move with their parents. See: https://github.com/cocos2d/cocos2d-iphone/issues/570
You need to change the design of your game so that your hero moves, and the obstacles stay in the same position. Then you implement a camera like mechanism to follow your moving hero.
We have used the same approach in our flappy bird tutorial.

Resources