Rotate a sprite along an axis - sprite-kit

In SpriteKit I need to rotate a sprite along an axis (e.g. the one that passes through the center of the sprite) just like a wheel to be spinned by the user.
I tried to use applyTorque function (to apply a force that is only angular and not linear), but I cannot handle the different forces caused by different movements on the screen (longer the touch on the screen, stronger the force to apply).
Can someone help me to understand how to deal with this problem?

Here is an answer that spins a ball according to how fast you swipe left / right:
class GameScene: SKScene {
let speedLabel = SKLabelNode(text: "Speed: 0")
let wheel = SKShapeNode(circleOfRadius: 25)
var recognizer: UIPanGestureRecognizer!
func pan(recognizer: UIPanGestureRecognizer) {
let velocity = recognizer.velocity(in: view!).x
// Play with this value until if feels right to you.
let adjustor = CGFloat(60)
let speed = velocity / adjustor
wheel.physicsBody!.angularVelocity = -speed
}
// Scene setup:
override func didMove(to view: SKView) {
removeAllChildren()
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
wheel.fillColor = .blue
wheel.physicsBody = SKPhysicsBody(circleOfRadius: 25)
wheel.physicsBody!.affectedByGravity = false
let wheelDot = SKSpriteNode(color: .gray, size: CGSize(width: 5, height:5))
wheel.addChild(wheelDot)
wheelDot.position.y += 20
wheel.setScale(3)
speedLabel.setScale(3)
speedLabel.position.y = (frame.maxY - speedLabel.frame.size.height / 2) - 45
recognizer = UIPanGestureRecognizer(target: self, action: #selector(pan))
view.addGestureRecognizer(recognizer)
addChild(wheel)
addChild(speedLabel)
}
override func didSimulatePhysics() {
speedLabel.text = "Speed: \(abs(Int(wheel.physicsBody!.angularVelocity)))"
}
}

Here is a basic example of spinning a wheel clockwise or counterclockwise depending on if you press on left / right side of screen. Hold to increase speed:
class GameScene : SKScene {
enum Direction { case left, right }
var directionToMove: Direction?
let wheel = SKShapeNode(circleOfRadius: 25)
let speedLabel = SKLabelNode(text: "Speed: 0")
override func didMove(to view: SKView) {
// Scene setup:
anchorPoint = CGPoint(x: 0.5, y: 0.5)
removeAllChildren()
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
wheel.fillColor = .blue
wheel.physicsBody = SKPhysicsBody(circleOfRadius: 25)
wheel.physicsBody!.affectedByGravity = false
let wheelDot = SKSpriteNode(color: .gray, size: CGSize(width: 5, height:5))
wheel.addChild(wheelDot)
wheelDot.position.y += 20
wheel.setScale(3)
speedLabel.setScale(3)
speedLabel.position.y = (frame.maxY - speedLabel.frame.size.height / 2) - 45
addChild(wheel)
addChild(speedLabel)
}
// Change this to touchesBegan for iOS:
override func mouseDown(with event: NSEvent) {
// Change this to touches.first!.location(in: self) for iOS.
let location = event.location(in: self)
// Determine if touch left or right side:
if location.x > 0 {
directionToMove = .right
}
else if location.x < 0 {
directionToMove = .left
}
}
override func mouseUp(with event: NSEvent) {
// Stop applying gas:
directionToMove = nil
print("lol")
}
override func update(_ currentTime: TimeInterval) {
// This is how much speed we gain each frame:
let torque = CGFloat(0.01)
guard let direction = directionToMove else { return }
// Apply torque in the proper direction
switch direction {
case .left:
wheel.physicsBody!.applyTorque(torque)
case .right:
wheel.physicsBody!.applyTorque(-torque)
}
}
override func didSimulatePhysics() {
// Speedometer:
speedLabel.text = "Speed: \(abs(Int(wheel.physicsBody!.angularVelocity)))"
}
}

Related

Swift: Centre point of fingers in UIRotationGesture in wrong place in SKView?

I'm trying to build a board game whereby the board is built of sprites and you can look over them birds eye view style with an SKCamera node. I've gotten the pan, zoom and rotate down but they don't feel natural as wherever I put my fingers on the screen it will rotate about the centre of the camera node.
To remedy this, I was going to create a SKNode and place this in-between where the fingers are as an anchor for the camera's rotation and zooming.
However I can't get the location of the centre point of the fingers to line up with the right coords in the gamescene.
I've created some red boxes to debug and find my problem and looks as so:
Where-ever I place my fingers in the entire game scene to rotate it, the centre where it thinks it should be is always in that red blob.
The SKView is placed on the storyboard as a SpriteKit view and is bound to the left and right edges of the screen with top and bottom padding:
Inside of viewcontroller:
#IBOutlet weak var Gameview: SKView!
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size:Gameview.frame.size)
Gameview.presentScene(scene)
}
Inside of GameScene.swift, let a = sender.location(in: self.view) seems to be where the problem lies.
class GameScene: SKScene, UIGestureRecognizerDelegate {
var newCamera: SKCameraNode!
let rotateRec = UIRotationGestureRecognizer()
let zoomRec = UIPinchGestureRecognizer()
//let panRec = UIPanGestureRecognizer()
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer)
-> Bool {return true}
override func didMove(to view: SKView) {
rotateRec.addTarget(self, action: #selector(GameScene.rotatedView (_:) ))
rotateRec.delegate = self
self.view!.addGestureRecognizer(rotateRec)
zoomRec.addTarget(self, action: #selector(GameScene.zoomedView (_:) ))
zoomRec.delegate = self
self.view!.addGestureRecognizer(zoomRec)
//panRec.addTarget(self, action: #selector(GameScene.pannedView (_:) ))
//self.view!.addGestureRecognizer(panRec)
newCamera = SKCameraNode()
newCamera.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
self.addChild(newCamera)
self.camera = newCamera
//drawBoard()
//I removed this function as it had nothing to do with the question
}
#objc func rotatedView(_ sender:UIRotationGestureRecognizer) {
print(sender.location(in: self.view))
let square = SKSpriteNode(color: #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1), size: CGSize(width: 10, height: 10))
let a = sender.location(in: self.view)
let b = -a.x
let c = -a.y
let d = CGPoint(x: b, y: c)
square.position = d
self.addChild(square)
newCamera.zRotation += sender.rotation
sender.rotation = 0
if sender.state == .ended {
let rotateAmount = abs(Double(newCamera.zRotation) * Double(180) / Double.pi)
let remainder = abs(rotateAmount.truncatingRemainder(dividingBy: 90))
//print(rotateAmount)
//print(remainder)
if remainder < 10 {
newCamera.zRotation = CGFloat((rotateAmount-remainder)*Double.pi/180)
} else if remainder > 80 {
newCamera.zRotation = CGFloat((rotateAmount-remainder+90)*Double.pi/180)
}
}
}
#objc func zoomedView(_ sender:UIPinchGestureRecognizer) {
let pinch = SKAction.scale(by: 1/sender.scale, duration: 0.0)
newCamera.run(pinch)
sender.scale = 1.0
}
//#objc func pannedView(_ sender:UIPanGestureRecognizer) {
// sender.translation(in: )
//}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
let previousLocation = touch.previousLocation(in: self)
let deltaY = location.y - previousLocation.y
let deltax = location.x - previousLocation.x
newCamera!.position.y -= deltaY
newCamera!.position.x -= deltax
}
}
}
I did remove the function drawboard() as it was redundant in context to the question.
You needed to convert the coords from the sender.location to the coords in the skview using the functions shown in the page:
https://developer.apple.com/documentation/spritekit/skscene
--> https://developer.apple.com/documentation/spritekit/skscene/1520395-convertpoint
in the rotatedview() function, putting the code:
let bluesquare = SKSpriteNode(color: #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1), size: CGSize(width: 10, height: 10))
let a = sender.location(in: self.view)
bluesquare.position = self.convertPoint(fromView: a)
self.addChild(bluesquare)
...will add blue sprites where the centre of your two fingers are.

How to make shape not to go to GameOver? -SpriteKit

I am creating a game where there is a square shape and every time the player taps on the square, it goes to GameOver scene. All I want to do is when the square shape is tapped, it will be allotted different position of the screen to be tapped on the squares.
Here is my code:
let touch:UITouch = touches.first!
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name
{
//The first ball that shows up
if name == "startball"
{
print("Touched", terminator: "")
addBall(ballSize)
self.addChild(score)
}
else if name == "shape"{
scoreCount += 1
addBall(ballSize)
audioPlayer.play()
}
}
else {
let scene = GameOver(size: self.size)
scene.setMyScore(0)
let skView = self.view! as SKView
skView.ignoresSiblingOrder = true
scene.scaleMode = .resizeFill
scene.size = skView.bounds.size
scene.setMessage("You Lost!")
scene.setEndGameMode(va)
gameTimer.invalidate()
shownTimer.invalidate()
print(" timers invalidated ", terminator: "")
ran = true
skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25))
}
if firstTouch {
shownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.decTimer), userInfo: nil, repeats: true)
gameTimer = Timer.scheduledTimer(timeInterval: TIME_INCREMENT, target:self, selector: Selector("endGame"), userInfo: nil, repeats: false)
firstTouch = false
}
if touchCount > 5 {
for touch: AnyObject in touches {
let skView = self.view! as SKView
skView.ignoresSiblingOrder = true
var scene: Congratz!
scene = Congratz(size: skView.bounds.size)
scene.scaleMode = .aspectFill
skView.presentScene(scene, transition: SKTransition.doorsOpenHorizontal(withDuration: 1.0))
}
}
touchCount += 1
}
override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
}
func endGame(){
shownTimer.invalidate()
gameTimer.invalidate()
let scene = GameOver(size: self.size)
scene.setMyScore(scoreCount)
if let skView = self.view {
skView.ignoresSiblingOrder = false
scene.scaleMode = .resizeFill
scene.size = skView.bounds.size
scene.setMessage("Times up")
skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25))
}
}
override func addBall(_ size: Int) {
// Add the ball
let currentBall = SKShapeNode(circleOfRadius: CGFloat(size))
let viewMidX = view!.bounds.midX
let viewMidY = view!.bounds.midY
currentBall.fillColor = pickColor()
currentBall.position = randomBallPosition()
if scoreCount != 0{
if scoreCount == 1{
self.addChild(score)
self.addChild(timeLeftLabel)
self.childNode(withName: "welcome")?.removeFromParent()
}
self.childNode(withName: "ball")?.run(getSmaller)
self.childNode(withName: "ball")?.removeFromParent()
}
currentBall.name = "ball"
self.addChild(currentBall)
}
func addSquare(_ size: Int) {
// Add the square
let shape = SKShapeNode(rectOf: CGSize(width:CGFloat(size), height:CGFloat(size)))
shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath
shape.fillColor = pickColor()
shape.position = randomBallPosition()
shape.name = "shape"
self.addChild(shape)
}
func randomBallPosition() -> CGPoint {
let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1)))
let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1)))
return CGPoint(x: xPosition, y: yPosition)
}
What I would suggest would be to make something like an enum for the different shapes, so you can keep track of what shape you're using.
enum GameShape: Int {
case circle = 0
case square = 1
}
Then create a GameShape property at the top of your GameScene:
var currentShape: GameShape = .circle
Then you could create some sort of updateShape method, which you could call in your touchesBegan method instead of just addBall
func updateShape(shapeSize: CGSize) {
switch currentShape {
case .circle:
addCircle(shapeSize)
case .square:
addSquare(shapeSize)
default:
break
}
// However you want to setup the condition for changing shape
if (condition) {
currentShape = .square
}
}
func addBall(_ size: CGSize) {
// Add the ball
}
func addSquare(_ size: CGSize) {
// Add the square
}
Now in your touchesBegan method, instead of calling addBall(size, you could call updateShape:
override func touchesBegan(_ touches: Set<UITouch>!, with event: UIEvent?) {
// Setup your code for detecting position for shape origin
updateShape(shapeSize)
}
EDIT - Your code is a mess. You really should take the time to make sure it's properly formatted when you submit it, otherwise it's really hard to help you. Indentation helps to see where a closure begins and ends. From what I can tell, it looks like you have two or more functions nested within your addBall method. This is not good. I tried my best to clean it up for you. You'll still need to write the code to make the shape a square, but I've lead you in the right direction to start to make that happen:
func addBall(_ size: CGSize) {
// Add the ball
let currentBall = SKShapeNode(circleOfRadius: CGFloat(size))
let viewMidX = view!.bounds.midX
let viewMidY = view!.bounds.midY
currentBall.fillColor = pickColor()
shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath
shape.fillColor = pickColor()
currentBall.position = randomBallPosition()
shape.position = randomBallPosition()
self.addChild(shape)
if scoreCount != 0{
if scoreCount == 1{
self.addChild(score)
self.addChild(timeLeftLabel)
self.childNode(withName: "welcome")?.removeFromParent()
}
self.childNode(withName: "ball")?.run(getSmaller)
self.childNode(withName: "ball")?.removeFromParent()
}
currentBall.name = "ball"
shape.name = "ball"
self.addChild(currentBall)
}
func addSquare(_ size: CGSize) {
// Add the square
}
func randomBallPosition() -> CGPoint {
let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1)))
let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1)))
return CGPoint(x: xPosition, y: yPosition)
}
Now the above code assumes you have some property named shape because from what I could tell you never explicitly instantiated that, but you begin manipulating it.

moving pacman in swift

i am brand new to swift and i am trying to program a pacman. i am trying to move the pacman to the direction of the swipe, so far i have managed to move it to the edges of the screen, the problem is that when i try to move it not from the edge of the screen but in the middle of the swipe action, it just goes to the edge of the screen and moves to the swipe direction, here is the code for one direction:
var x = view.center.x
for var i = x; i > 17; i--
{
var origin: CGPoint = self.view.center
var move = CABasicAnimation(keyPath:"position.x")
move.speed = 0.13
move.fromValue = NSValue(nonretainedObject: view.center.x)
move.toValue = NSValue(nonretainedObject: i)
view.layer.addAnimation(move, forKey: "position")
view.center.x = i
}
the thing is that i know the problem which is when i swipe to the direction that i want the for loop will not wait for the animation to stop but it will finish the loop in less than a second and i need sort of delay here or other code.
This was an interesting question, so I decided to make an example in SpriteKit. There isn't any collision detection, path finding or indeed even paths. It is merely an example of how to make 'Pac-Man' change direction when a swipe occurs.
I have included the GameScene below:
class GameScene: SKScene {
enum Direction {
case Left
case Right
case Up
case Down
}
lazy var openDirectionPaths = [Direction: UIBezierPath]()
lazy var closedDirectionPaths = [Direction: UIBezierPath]()
lazy var wasClosedPath = false
lazy var needsToUpdateDirection = false
lazy var direction = Direction.Right
lazy var lastChange: NSTimeInterval = NSDate().timeIntervalSince1970
var touchBeganPoint: CGPoint?
let pacmanSprite = SKShapeNode(circleOfRadius: 15)
override func didMoveToView(view: SKView) {
let radius: CGFloat = 15, diameter: CGFloat = 30, center = CGPoint(x:radius, y:radius)
func createPaths(startDegrees: CGFloat, endDegrees: CGFloat, inout dictionary dic: [Direction: UIBezierPath]) {
var path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startDegrees.toRadians(), endAngle: endDegrees.toRadians(), clockwise: true)
path.addLineToPoint(center)
path.closePath()
dic[.Right] = path
for d: Direction in [.Up, .Left, .Down] {
path = path.pathByRotating(90)
dic[d] = path
}
}
createPaths(35, 315, dictionary: &openDirectionPaths)
createPaths(1, 359, dictionary: &closedDirectionPaths)
pacmanSprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
pacmanSprite.fillColor = UIColor.yellowColor()
pacmanSprite.lineWidth = 2
if let path = openDirectionPaths[.Right] {
pacmanSprite.path = path.CGPath
}
pacmanSprite.strokeColor = UIColor.blackColor()
self.addChild(pacmanSprite)
updateDirection()
// Blocks to stop 'Pacman' changing direction outside of a defined path?
//375/25 = 15 width
//666/37 = 18 height
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
touchBeganPoint = positionOfTouch(inTouches: touches)
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touchStartPoint = touchBeganPoint,
touchEndPoint = positionOfTouch(inTouches: touches) {
if touchStartPoint == touchEndPoint {
return
}
let degrees = atan2(touchStartPoint.x - touchEndPoint.x,
touchStartPoint.y - touchEndPoint.y).toDegrees()
var oldDirection = direction
switch Int(degrees) {
case -135...(-45): direction = .Right
case -45...45: direction = .Down
case 45...135: direction = .Left
default: direction = .Up
}
if (oldDirection != direction) {
needsToUpdateDirection = true
}
}
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
touchBeganPoint = nil
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if let nodes = self.children as? [SKShapeNode] {
for node in nodes {
let p = node.position
let s = node.frame.size
//let s = node.size
if p.x - s.width > self.size.width {
node.position.x = -s.width
}
if p.y - s.height > self.size.height {
node.position.y = -s.height
}
if p.x < -s.width {
node.position.x = self.size.width + (s.width / 2)
}
if p.y < -s.height {
node.position.y = self.size.height + (s.height / 2)
}
if needsToUpdateDirection || NSDate().timeIntervalSince1970 - lastChange > 0.25 {
if let path = wasClosedPath ? openDirectionPaths[direction]?.CGPath : closedDirectionPaths[direction]?.CGPath {
node.path = path
}
wasClosedPath = !wasClosedPath
lastChange = NSDate().timeIntervalSince1970
}
updateDirection()
}
}
}
// MARK:- Helpers
func positionOfTouch(inTouches touches: Set<NSObject>) -> CGPoint? {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
return location
}
return nil
}
func updateDirection() {
if !needsToUpdateDirection {
return
}
pacmanSprite.removeActionForKey("Move")
func actionForDirection() -> SKAction {
let Delta: CGFloat = 25
switch (direction) {
case .Up:
return SKAction.moveByX(0.0, y: Delta, duration: 0.1)
case .Down:
return SKAction.moveByX(0.0, y: -Delta, duration: 0.1)
case .Right:
return SKAction.moveByX(Delta, y: 0.0, duration: 0.1)
default:
return SKAction.moveByX(-Delta, y: 0.0, duration: 0.1)
}
}
let action = SKAction.repeatActionForever(actionForDirection())
pacmanSprite.runAction(action, withKey: "Move")
needsToUpdateDirection = false
}
}
The repository can be found here
I have added the MIT license, so you can fork this repository if you wish. I hope this helps.

Swift | I'm trying to rotate a sprite and change the direction of the rotation ever time I tap

I want to rotate a single sprite indefinitely, and every time I tap the button, I want the sprite to rotate in the opposite direction (back and forth from clockwise to counter-clockwise etc.
Below is the code that I have:
http://pastebin.com/Avj8Njwt
class GameScene: SKScene {
var center = SKSpriteNode()
var bg = SKSpriteNode()
var bigCircle = SKSpriteNode()
let counterClockwise = SKAction.rotateByAngle(CGFloat(3.14), duration:1)
let clockwise = SKAction.rotateByAngle(CGFloat(-3.14), duration:1)
var spin = SKAction()
override func didMoveToView(view: SKView) {
//Background
var bgTexture = SKTexture(imageNamed: "images/bg.png")
bg = SKSpriteNode(texture:bgTexture)
bg.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(center)
//Center Circle
var bigCircleTexture = SKTexture(imageNamed: "images/bigCircle.png")
bigCircle = SKSpriteNode(texture:bigCircleTexture)
bigCircle.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(bigCircle)
//Center Triangle
var centerTexture = SKTexture(imageNamed: "images/center.png")
center = SKSpriteNode(texture:centerTexture)
center.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(center)
spin = clockwise
center.runAction(SKAction.repeatActionForever(spin))
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
if spin == clockwise {
spin = counterClockwise
}
else {
spin = clockwise
}
center.runAction(SKAction.repeatActionForever(spin))
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
Your problem is you're not removing the old SKAction trying to rotate your SKSpriteNode. To do that you need to keep track of which way your sprite is rotating. If I was going to implement this I would subclass SKSpriteNode, like so:
class RotatingSprite: SKSpriteNode {
// This is used to keep track of which way the sprite is rotating.
enum Direction {
case Left, Right
mutating func inverse() {
switch self {
case .Left : self = .Right
case .Right: self = .Left
}
}
}
// These names will be the keys used when running an action.
// This will allow you to stop the rotate-left or rotate-right actions.
static let rotateLeftName = "RotateLeftAction"
static let rotateRightName = "RotateRightAction"
var rotationDirection: Direction? {
didSet {
if let r = rotationDirection {
switch r {
// Checks the sprite isn't already rotating to the left.
// If it isn't, make the sprite rotate to the left.
case .Left where oldValue != .Left:
rotateLeft()
case .Right where oldValue != .Right:
rotateRight()
default:
break
}
}
}
}
private func rotateLeft() {
// Remove the action rotating the sprite to the right.
self.removeActionForKey(RotatingSprite.rotateRightName)
// And start the action rotating the sprite to the left.
let rotateAction = SKAction.rotateByAngle(-CGFloat(M_PI), duration: 1.0)
self.runAction(SKAction.repeatActionForever(rotateAction), withKey: RotatingSprite.rotateLeftName)
}
private func rotateRight() {
self.removeActionForKey(RotatingSprite.rotateLeftName)
let rotateAction = SKAction.rotateByAngle(CGFloat(M_PI), duration: 1.0)
self.runAction(SKAction.repeatActionForever(rotateAction), withKey: RotatingSprite.rotateRightName)
}
}
Now you can use RotatingSprite like so:
class GameScene: SKScene {
let rotatingSprite = RotatingSprite(texture:bgTexture)
override func didMoveToView(view: SKView) {
rotatingSprite.position = CGPoint(x: frame.midX, y: frame.midY)
self.addChild(rotatingSprite)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// If the sprite isn't turning you've got to set it off.
if rotatingSprite.rotationDirection == nil {
rotatingSprite.rotationDirection = .Left
// If it is turning, change its direction.
} else {
rotatingSprite.rotationDirection!.inverse()
}
}
}
Hope that helps!
It is extremely easy to achieve this. Try this ,
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
[sprite removeAllActions];
SKAction *action;
if (isClockWise)
{
action = [SKAction rotateByAngle:M_PI duration:1];
}
else
{
action = [SKAction rotateByAngle:-M_PI duration:1];
}
isClockWise = !isClockWise;
[sprite runAction:[SKAction repeatActionForever:action]];
}
Where sprite is SKSpriteNode and initiate isClockWise to Yes or No depending on your initial movement direction.
A quick and dirty way to do this is the following:
import SpriteKit
class GameScene: SKScene {
var center = SKSpriteNode()
var bg = SKSpriteNode()
var bigCircle = SKSpriteNode()
let counterClockwise = SKAction.rotateByAngle(CGFloat(3.14), duration:1)
let clockwise = SKAction.rotateByAngle(CGFloat(-3.14), duration:1)
var spin = SKAction()
// this is used to identify which direction we are going in. When we change it spin is changed as well
var isClockwise: Bool = true {
didSet {
if isClockwise {
spin = clockwise
} else {
spin = counterClockwise
}
}
}
let actionKey = "spin" // this is used to identify the SKAction
override func didMoveToView(view: SKView) {
//Background
var bgTexture = SKTexture(imageNamed: "images/bg.png")
bg = SKSpriteNode(texture:bgTexture)
bg.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(center)
//Center Circle
var bigCircleTexture = SKTexture(imageNamed: "images/bigCircle.png")
bigCircle = SKSpriteNode(texture:bigCircleTexture)
bigCircle.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(bigCircle)
//Center Triangle
var centerTexture = SKTexture(imageNamed: "images/center.png")
center = SKSpriteNode(texture:centerTexture)
center.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(center)
isClockwise = true // set the initial direction to clockwise
center.runAction(SKAction.repeatActionForever(spin), withKey: actionKey)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// remove the existing spin action
center.removeActionForKey(actionKey)
// reset the direction (this will automatically switch the SKAction)
isClockwise = !isClockwise
center.runAction(SKAction.repeatActionForever(spin), withKey: actionKey)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
You need to remove the action before you apply a new one - you can selectively remove the action by calling runAction(action:,withKey:). This enables you to be able to remove that same action using the same key. The logic for changing spin is in didSet for the isClockwise var declaration.
It was as simple as placing center.removeAllActions in each if statement to make sure the sprite isn't currently moving when the direction is supposed to be changed.

Swift SpriteKit get visible frame size

I have been trying to create a simple SpriteKit app using Swift. The purpose is to have a red ball re-locate itself on the screen when clicked on. But the variables self.frame.width and self.frame.height do not return the boundaries of the visible screen. Instead they return boundaries of the whole screen. Because I am choosing the location of the ball at random I need the visible boundaries. Couldn't find an answer after hours of research. How can I achieve this?
var dot = SKSpriteNode()
let dotScreenHeightPercantage = 10.0
let frameMarginSize = 30.0
override func didMoveToView(view: SKView) {
var dotTexture = SKTexture(imageNamed: "img/RedDot.png")
dot = SKSpriteNode(texture: dotTexture)
dot.size.height = CGFloat( Double(self.frame.height) / dotScreenHeightPercantage )
dot.size.width = dot.size.height
dot.name = "dot"
reCreateDot()
}
func reCreateDot() {
dot.removeFromParent()
let dotRadius = Double(dot.size.height / 2)
let minX = Int(frameMarginSize + dotRadius)
let maxX = Int(Double(self.frame.width) - frameMarginSize - dotRadius)
let minY = Int(frameMarginSize + dotRadius)
let maxY = Int(Double(self.frame.height) - frameMarginSize - dotRadius)
let corX = randomInt(minX, max: maxX)
let corY = randomInt(minY, max: maxY)
println("result: \(corX) \(corY)")
dot.position = CGPoint(x: corX, y: corY)
self.addChild(dot)
}
func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
if node.name == "dot" {
println("Dot tapped.")
reCreateDot()
}
}
}
Adding this bit of code to the GameViewController seems to have fixed the issue.
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
scene.size = skView.bounds.size
skView.presentScene(scene)
Thank you #ABakerSmith for pointing me in the right direction.
I tried with your code and setting the size of the scene fixed the issue. If you're unarchiving the scene, its size will be the size set in the sks file. Therefore you need to set the size of the scene to the size of your SKView.
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
scene.size = skView.frame.size
skView.presentScene(scene)
}
or in didMoveToView of your SKScene subclass:
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
self.size = view.frame.size
}