Swift 5, iOS 14
Wrote this code to fade in a sprite node... works ok, but Xcode says this, which makes no sense since I am using timer within the loop.
Initialization of immutable value 'timer' was never used; consider replacing with assignment to '_' or removing it
let timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
node2Delete?.alpha -= 0.1
ghost.alpha += 0.1
if node2Delete?.alpha == 0 {
node2Delete?.removeFromParent()
timer.invalidate()
}
}
And it doesn't complain about the timer within the loop not being defined? Is this a bug or am I missing something?
Is there a better way to do this? Is the timer I set here actually being cancelled?
You want to use SKAction not Timer here, so you can replace all your code with the below.
Create two variables which hold the fade logic, one for fade in, the other for fade out.
Run fadeIn on your ghost node. The ghost node will gradually appear over the course of 5 seconds.
Run fadeOuton your node2Delete node, this will gradually fade the alpha to 0 over the course of 5 seconds. Once completed, we remove the node from it's parent.
let fadeOut = SKAction.fadeAlpha(to: 0.0, duration: 5.0)
let fadeIn = SKAction.fadeAlpha(to: 1.0, duration: 5.0)
ghost.run(fadeIn)
node2Delete.run(fadeOut){
self.node2Delete.removeFromParent()
}
Related
I'm writing an application that displays chemical reactions and molecules in 3D. I read in all the values and positions of each atom from a text file and I am creating each atom shape with SCNSpheres. I have all the other values I need read in properly, but I can't figure out how to add keyframe animations to each node object in my scene.
I set up the molecules like this in ViewController.swift
func makeAtom(atomName: String, coords: [Double], scene: SCNScene) {
guard let radius = atomRadii[atomName]?.atomicRadius else { return }
atoms.append(Atom(name: atomName, x: coords[0], y: coords[1], z: coords[2], radius: radius, positions: []))
let atomGeometry = SCNSphere(radius: CGFloat(radius))
let atomNode = SCNNode(geometry: atomGeometry)
atomNode.position = SCNVector3(coords[0], coords[1], coords[2])
scene.rootNode.addChildNode(atomNode)
atomNodes.append(atomNode)
}
I know that the CAKeyframeAnimations are supposed to be set up like this
let animation = CAKeyframeAnimation()
animation.keyPath = "position.y"
animation.values = [0, 300, 0]
animation.keyTimes = [0, 0.5, 1]
animation.duration = 2
animation.isAdditive = true
vw.layer.add(animation, forKey: "move")
I just don't know where I should be declaring these animations and how the layers factor into all this. What layer should I be adding the animations to? And how can I trigger them to play? I've been searching all over the internet for help with this but I can't find anything that just shows a simple implementation.
I can provide more code if need be, I'm pretty new to StackOverflow and want to make sure I'm doing this right.
You can do it different ways, but I like this method: 58001288 (my answer here) as you can pre-build some animations using scenekit and then run them as a sequence.
Per the comment.. needed more room.
A sequence is a fixed thing. You can start, repeat, and stop it. However, it's hard to interact with it during phases.
If you really need to do that, then one way is to break up your sequence into its parts and call the next one yourself after a completion handler of the current one. I keep an array and a counter so that I know where I am. So basically it's just a queue of actions that I manage - if I'm on a certain step and the button is pressed, then I can cancel all current actions, set the desired effect, and restart it.
Edit:
The completion handler calls itself at the end of the function and advances its own array count so that the next one in the list can be called. This is obviously a bit dangerous, so I would use sparingly, but that's how I did it. I started mine on a timer, then don't forget to clean it up. I had a global GAME_ACTIVE switch and within the code I checked for it before calling myself again.
Edit2: This is actually a moveTo, but it's still just a custom set of SCNActions that calls itself when complete based on duration so that it immediately goes to the next one without a delay.
func moveTo()
{
let vPanelName = moves[moveCount]
let vLaneNode = grid.gridPanels[vPanelName]!.laneNodes[lane]
let vAction = SCNAction.move(to: vLaneNode.presentation.position, duration: TimeInterval(data.getAttackSpeed(vGameType: gameType)))
node.runAction(vAction, completionHandler:
{
self.moveCount += 1
if(self.moveCount >= self.moves.count - 1)
{
self.killMe(vRealKill: false)
return
}
else
{
self.moveTo()
}
})
}
I'm working with Swift language. I wrote an animation for a timer that lasts for 30 seconds and is full. Now I want to stop this animation, but I do not know how! I want to be able to start again from the beginning. Animation.
Thanks if you have a solution or a method that helps me🙏
You can try
self.myView.layer.removeAllAnimations()
Two possible ways:
Somewhere store variable for total time. And in every timer repeat increase this value. When total time reaches 30 seconds, remove animation
When you start animation, set action which gets executed after specific time
First possible way:
var time: Double = 0
#objc func timerChangedValue() {
time += 1
if time == 30 {
view.layer.removeAllAnimations()
view.layoutIfNeeded()
}
}
Second possible way:
DispatchQueue.main.asyncAfter(deadline: .now() + 30) {
self.view.layer.removeAllAnimations()
self.view.layoutIfNeeded()
}
I'm trying to get an SKShapeNode to move and fade from 0 alpha to 1 alpha over a 2 second period and then delete itself. The moving part is fine, but when I try to add the fadeIn it fades in very very quickly (in about 0.2 seconds) and repeats itself, so it ends up looking like the SKShapeNode is flashing. Can anyone help?
Here is my code:
func startMoving(){
alpha = 0
let move = SKAction.moveBy(x: moveX, y: moveY, duration: 2.0)
let fadeIn = SKAction.fadeIn(withDuration: 2.0)
let group = SKAction.group([move, fadeIn])
run(group, completion: {
self.removeFromParent()
})
}
Also, I'm a bit worried that self.removeFromParent() won't actually delete the instance of the node. I'm running this quite a few times, so want to make sure i'm properly taking care of it. I've tried self = nul, but that didn't work. Any suggestions?
the code you posted is working fine. Your bug is elsewhere.
I have a SKAction that runs an action if an area on the screen is touched. However I cannot get the SKanimate to only run through the SKarray once (both actions that is), it seems to run around 4 times. The count parameter doesn't seem to make any difference either. Any help on how to get it to run through the frames in the array just once then stop would be appreciated!
//Touch location check
for touch in touches {
let location = touch.location(in: self)
if myButton.contains(location) {
//run shoot animation.
MainGuy.run(SKAction.repeat(SKAction.animate(with: TextureArrayShoot, timePerFrame: 0.10), count: 1),withKey: "outlaw")
print ("touched")
let witchaction = SKAction.animate(with: TextureArrayWitch, timePerFrame: 0.20)
witch.run(witchaction)
missedLabel1.text = "Good Shot!"
}
}
Apologies - solved it. There were 3 arrays for sprites in a row, and the first one wasn't closed properly and encapsulating the other two, meaning the 'I' in for I in...was being used 3 times!
I would need help with this while loop - what I'm trying to do is slow down the whole process of removing and adding new circles while radius is changing every time this happens. I'm becoming really desperate, I've tried using both dispatch_after and sleep inside the loop (which I found online) but neither of them is suitable, they basically stop the whole app. If I put them in the while loop, nothing happens. Thanks in advance!
while radius < 100 {
self.removeAllChildren()
addCircle()
radius++
print(radius)
}
Basically you just need to do few simple things:
Wait for a certain duration and add a node to the scene
Repeat this step forever (or certain number of times)
Here is the example of how you can do it. The important part is action sequence. You create the step above, and repeat it forever. Each time you check radius value and based on that you stop the action (remove it by the key). And that's it. You can change spawning speed by changing action's duration parameter.
Using NSTimer might seem like an easier solution, but NSTimer doesn't respect node's (or scene's or view's) paused state. So, imagine this situation:
You start spawning of nodes
User receive phone call and app automatically goes to background
Because NSTimer is not automatically paused, the nodes will continue with spawning. So you have to take an additional step and invalidate/restart timer by your self. When using SKAction, this is done automatically. There are some other flaws of using NSTimer in SpriteKit, search SO about all that, there are some posts which covering all this.
import SpriteKit
class GameScene: SKScene{
var radius:UInt32 = 0
override func didMoveToView(view: SKView) {
startSpawning()
}
func startSpawning(){
let wait = SKAction.waitForDuration(0.5)
// let wait = SKAction.waitForDuration(1, withRange: 0.4) // randomize wait duration
let addNode = SKAction.runBlock({
[unowned self] in //http://stackoverflow.com/a/24320474/3402095 - read about strong reference cycles here
if(self.radius >= 30){
if self.actionForKey("spawning") != nil {
self.removeActionForKey("spawning")
}
}
self.radius++
let sprite = self.spawnNode()
sprite.position = CGPoint(x: Int(arc4random()) % 300, y: Int(arc4random()) % 300) // change this to randomize sprite's position to suit your needs
self.addChild(sprite)
})
//wait & add node
let sequence = SKAction.sequence([wait, addNode])
//repeat forever
runAction(SKAction.repeatActionForever(sequence), withKey: "spawning")
}
func spawnNode()->SKSpriteNode{
let sprite = SKSpriteNode(color: SKColor.purpleColor(), size: CGSize(width: 50, height: 50))
//Do sprite initialization here
return sprite
}
}
The sleep stops the whole app because you are running the loop on the main thread.
You can solve this problem in one of two ways...
1) Use an NSTimer. Set it to the amount of time you want to delay. Put the body of the loop in the timer's trigger function and disable the timer when it has been called enough times. This is the best solution.
2) Wrap the loop in a dispatch async block to a background thread and put a sleep in the loop. If you do this though, you will have to wrap the UI code in another dispatch async block that comes back to the main thread.