Control SCNAction with slider - swift

I'm looking for a solution for my problem:
I have defined a animation as SCNAction with the action editor in Xcode. Now I want to control it with a slider. So basically manipulating the slider shows a specific time/frame in the animation.
Right now, I can just pause/play the animation or reset it to the beginning. I achieved this with Swift code addressing the SCNAction from the action editor.
As far as I researched, there is no possibility
to animate a SCNAction to a specific time immediately and stop right there. That would work.
I'm also interested in other attempts if this is not achievable with SCNActions. It may be that this is not realizable at all. Thank you.

I found a solution: I loaded a CAAnimation from a .dae file(For this look here:https://stackoverflow.com/a/24924702/9625548, bit outdated but still usable).
With the SCNAnimationPlayer I can address the CAAnimation with a key. With the following
code I can control my animation with a UISlider:
let moment: TimeInterval = TimeInterval(self.animationTimeSlider.value)
guard let animationPlayer: SCNAnimationPlayer = node.animationPlayer(forKey: key) else{
return
}
animationPlayer.animation.timeOffset = moment
animationPlayer.play()
animationPlayer.speed = 0.0
Basically, I read the thumb and convert it to TimerInterval. I'm looking for the SCNAnimationPlayer and aborting if no SCNAnimationPlayer is found for the given key. Then I set the .timeOffset to the moment I want to display. With play(), the animation starts from the beginning + .timeOffset. Finally, set the .speed to zero. the animation is not running but shows the moment.
Attention: If you let your animation running and also manipulating it in that way, you have to reset it. Otherwise it is getting messed up. You can catch that case with a boolean that saves if you let your animation run normally. Then you know you have to reset it before manipulating with the slider. For example like this:
node.removeAllAnimations()
node.addAnimation(animation, forKey: key)
self.sceneView.scene.rootNode.animationPlayer(forKey: key)?.paused = true

Related

How to get info about completion of one of my animations in Unity?

I have monster named Fungant in my 2D platform game.
It can hide as mushroom and rise to his normal form.
I try to handle it in code, but I don't know how to get information about finished animation (without it, animation of rising and hiding always was skipped).
I think the point there is to get info about complete of the one of two animations - Rise and Hide.
There is current code:
if (
fungantAnimator.GetCurrentAnimatorStateInfo(0).IsName("Fungant Rise")
)
{
fungantAnimator.SetBool("isRising", false);
isRisen = true;
fungantRigidbody.velocity = new Vector2(
walkSpeed * Mathf.Sign(
player.transform.position.x - transform.position.x),
fungantRigidbody.velocity.y
);
}
if (fungantAnimator.GetCurrentAnimatorStateInfo(0).IsName("Fungant Hide"))
{
fungantAnimator.SetBool("isHiding", false);
isRisen = false;
}
I try this two ways:
StateMachineBehaviour
I would like to get StateMachineBehaviour, but how to get it?
No idea how to process this further.
AnimationEvents
Tried to do with animation event but every tutorial have list of functions to choose (looks easy), but in my Unity I can write Function, Float, Int, String or select object (what I should do?).
I decided to write test() function with Debug only inside, and create AnimationEvents with written "test()" in function field, but nothing happens.
Same as above, no more ideas how to process this further.
I personally would use animation events for this. Just add an event to the animation and then the event plays a function after the animation transition is finished.
For more information on how to use animation events you can click here.
This post may also help you to add an event when the animation is finished.
I hope this answer helps you to solve this problem.

Xcode 11 Action Editor? How to invoke?

In an earlier post I asked about the right settings for initializing a SCNParticleEngine. With some hints from Zay
I managed to get both the SCNP and code paths to work – almost identically. Except that the SCNP path had the particles shrinking over time while the coding path did not.
Turns out that buried inside the SCNP file is a dictionary entry “Size” which is a SCNParticlePropertyController. Here’s the code from the debugger:
The gotcha is that when I open the SCNP file in the editor, I can see the stars being animated etc. But there is no sign of an Action or any affordance to open such an editor. Now, this may be related to the fact that the SCNP file is all about the PE parameters for initializing the PE. There is NOT an actual node or object on the stage. One thought is you need to have an editable action or Xcode won’t open the Action editor?
How this action got there or how I might edit it is not clear. I assume someone put it in the SCNP in an earlier version of Xcode. Then the Action was forgotten. Or something like that. It may simply be a bug/corrupted SCNP file.
As you mention this is Core Animation animation driving SCNParticlePropertySize. It is possible to configure it in the SceneKit scene editor via the Attributes inspector (not the Action editor).
To be able to control the size of your particles over time (i.ex. let them shrink) using code only, you have to use a SCNPropertyController and a CAKeyframeAnimation like so:
// ANIMATE PARTICLE SIZE OVER TIME
let animationSize = CAKeyframeAnimation()
animationSize.values = [0.7, 0.3, 0.2, 0.0]
animationSize.keyTimes = [0.0, 0.125, 0.3, 1.0]
animationSize.duration = CFTimeInterval(10.0)
animationSize.calculationMode = .cubic
animationSize.timingFunction = CAMediaTimingFunction.init(name: .linear)
and then you do:
// SET PROPERTY CONTROLLER
let sizeController = SCNParticlePropertyController(animation: animationSize)
myParticleSystem.propertyControllers = [SCNParticleSystem.ParticleProperty.size: sizeController]
with the same approach you can animate the particle colours in a changing sequence over time.

NSImageView update delayed when set from an NSTimer

I'm working on a project in Swift that requires strict control of image display and removal timings in certain sections. I'm finding that when I set the image property of an NSImageView from inside a block that's fired by a Timer, the actual display of the image on the screen is delayed by up to a second after the assignment is complete. (This is measured by eyeballing it and using a stopwatch to gauge the time between when an NSLog line is written and when the image actually appears on-screen.)
Triggering image display with a click appears to happen instantaneously, whether it's done by setting the image property of an existing NSImageView, or constructing one on the spot and adding it as a subview.
I have attempted to reduce the behavior down to a fairly simple test case, which, after basic setup of the view (loading the images into variables and laying out several target image locations, which are NSImageViews stored to the targets array), sets a Timer, with an index into the targets array stored in its userInfo property, to trigger the following method:
#objc func testATimer(fromTimer: Timer) {
if let targetLocation = fromTimer.userInfo as? Int {
NSLog("Placing target \(targetLocation)")
targets[targetLocation].image = targetImage
OperationQueue.main.addOperation {
let nextLocation = targetLocation + 1
if (nextLocation < self.targets.count) {
NSLog("Setting timer for target \(nextLocation)")
let _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(ViewController.testATimer(fromTimer:)), userInfo: nextLocation, repeats: false)
}
}
}
}
The amount of time observed between the appearance of the log entry "Placing target x" and that of the image that is set to be displayed in the very next line seems to average between 0.3 and 0.6 seconds. This is far beyond the delay that this project can tolerate, as the image will only be on screen for a total of 1 second at a time.
My best guess as to why this is happening is that it is something to do with Timers running on a separate thread from the main display thread; however, I do not have enough experience with multi-threaded programming to know exactly how to mitigate that.
Any assistance would be most appreciated, and if I've left out information that would make answering easier (or possible) I'm more than happy to give it.
Well, after poking at it with some helpful people on in #macdev on irc.freenode.net, I found that the source of the problem was the program scaling the image down on the fly every time it set it to the NSImageView. Reducing the size of the image ahead of time solved the problem. (As did setting the image once, then hiding and showing the NSImageView instead.)

Proper transition between SpriteKit Animations

I have an idle player animation and I want to do a smooth transition between some animations. The idle animation is the default one and from that transition I want to be able to switch to another state(let's say fight) and then back to idle. The code for the idle character animation is currently like :
self.addChild(playerAnimation)
playerAnimation.runAction(SKAction.repeatActionForever(
SKAction.animateWithTextures(playerAnimationManager.idleManAnimation.textureArray, timePerFrame: 0.1)))
Now, this is scheduled to go on forever for now, but I would need to intercept it and add a new animation on top of that (which is the same character, in a new state). I was thinking that I should stop the idle animation, switch to the new one and then back to idle when finished but I am not convinced that this is the best way of chaining animations and I haven't really found a good resource explaining how to go about it.
Any suggestions ? Thanks !
Depending on how short your texture array is, you might be able to do this.
I will try to explain without code seeing how I use objective C and you use Swift
First make a property or variable that can be called by any subroutine in this class file. It should be Boolean and should be set to NO. You could call it idleFlag.
Next make a method that changes the animation to fight mode. This change would be by removing the idle animation and replacing it with the fight animation. This method also set's idleFlag to NO. Let's call the method "beginFightAnim"
And last, in your repeatActionForEver idle animation, right after your animateWithTextures animation, add a runBlock animation. In this block define a static variable (one that will be remembered in the calling of the block over and over) and increment it by +1, add an "if statement" that looks something like this -> if (my_static_var == number_of_frames_in_texture_animations && idleFlag). And in the "if statement" set the static variable to 0 and call "beginFightAnim"
After this all you have to do to change the animation is set idleFlag to YES.
Hope it works!
If you have any problems, please comment below.
I want to do a series of examples to make it easier to understand the matter. Suppose you have your node called playerAnimation, a typical atlasc with a plist where you have
player-idle1.png
player-idle2.png
player-idle3.png
...
If you want to intercept in real-time your animation to know what frame is running in that moment you can do:
override func update(currentTime: CFTimeInterval) {
if String(playerAnimation.texture).rangeOfString("player-idle") != nil {
print(String(playerAnimation.texture))
}
}
At this point, after you have assigned a "key" to your action (withKey:"idleAnimation") you could stop your specific idle action when you preefer to start the other next animation.
Another good thing is to build a structure to know everytime your player status and modify this variable each time you launch a new action or animation:
enum PlayerStatus: Int {
case Idle = 1
case Fight = 2
case Run = 3
case Jump = 4
case Die = 5
...
}
var currentStatus: PlayerStatus!

Beginning and End of animation using SKAction.animateWithTextures in Swift

I'm working on a little project in spritekit and can't quite figure something out. I am animating a sprite using SKAction.animateWithTextures and moving through and array. Works fine just like it should. The issue is that I would like to a function that starts when the animation starts and one when it ends. I see there is a .animationDidStart(CAAnimation), but because what I'm doing is not a CAAnimation I can't really use it. Is there something like this for the method I'm using? As you can may or may not be able to tell I'm still rather new to swift. Thanks for any help in advance.
I'd create a sequence of actions. First a block action to call your method you want called when the animation starts, then your animateWithTextures action, finally another block action that calls your finished method.
let startAction = SKAction.runBlock {
self.startAnimation()
}
let textureAction = SKAction.animateWithTextures...
let finishedAction = SKAction.runBlock {
self.finishedAnimation()
}
SKAction.sequence([startAction, textureAction , finishedAction])