I am using SceneKit to load a Collada (.dae) file.
Whatever I have tried, the animation repeats in a continuous loop whereas I only want it play once and then stop.
Here's the loading code where sceneView is my SCNView:
//Load the scene and play
let scene = SCNScene(named: "Scenes.scnassets/test4.dae")
sceneView.scene = scene
sceneView.autoenablesDefaultLighting = true
sceneView.allowsCameraControl = true
The scene loads correctly and the animation plays on loading as required, but in a continuous loop.
I have tried removing all animations as follows:
sceneView.scene?.rootNode.removeAllAnimations()
but this seems to have no effect.
I have also tried retrieving all animations and setting the repeatCount = 1 or even to 0
let url = NSBundle.mainBundle().URLForResource("Scenes.scnassets/test4", withExtension: "dae")
let sceneSource = SCNSceneSource(URL:url!, options: nil)
let animationIndentifiers = sceneSource?.identifiersOfEntriesWithClass(CAAnimation)
if let ids = animationIndentifiers
{
for id in ids {
let animation: CAAnimation = sceneSource!.entryWithIdentifier(id as! String, withClass: CAAnimation.self)! as! CAAnimation
animation.repeatCount = 1
}
}
I have also tried this another way:
let keys = sceneView.scene!.rootNode.animationKeys() //get all the animation keys
if let theKeys = keys {
for key in theKeys {
let animation = sceneView.scene?.rootNode.animationForKey(key as! String)
animation?.repeatCount = 1
}
}
but again no luck.
I can find nothing in the Collada file itself that is obviously causing the animation to repeat. However, I notice that the .dae file icon on my Mac disk has a play button and clicking this also plays the animation within the icon on a continuous loop.
Update:
I now notice that in the code above I am setting the constant 'animation' attributes and this is not copied back to the actual scene nodes. Also, the only animation in the .dae file is in a child node. So here's my next attempt:
//Get the child nodes
let children = scene?.rootNode.childNodes
//Initialise a childNode counter
var childCount = 0
//Iterate through the child nodes
if let theChildren = children {
for child in theChildren {
let keys = child.animationKeys() //get all the animation keys
//Iterate through the animations
if let theKeys = keys {
for key in theKeys {
let animation = child.animationForKey(key as! String)
println("Initial Repeat count: \(animation.repeatCount)")
animation.repeatCount = 1
//Remove existing animation
scene?.rootNode.childNodes[childCount].removeAnimationForKey(key as! String)
//Add amended animation
scene?.rootNode.childNodes[childCount].addAnimation(animation, forKey: key as! String)
}
}
childCount++
}
}
There is actually only one animation attached to one child node. (I have also tried setting this using the the actual animation id string in place of 'key' above.)
The above shows Initial Repeat count: inf
and on checking afterwards it is indeed set to 1.
However, the animation still runs in an infinite loop :-(
Any help to resolve this would be much appreciated.
Further update
I have now created a new Collada file with simple animation using Maya and for some reason one of the trials attempted above actually works:
func sceneSetup() {
let scene = SCNScene(named: "Scenes.scnassets/test10.dae")
let children = scene?.rootNode.childNodes
var childCount = 0
if let theChildren = children {
for child in theChildren {
let keys = child.animationKeys() //get all the animation keys
if let theKeys = keys {
for key in theKeys {
let animation = child.animationForKey(key as! String)
animation.repeatCount = 1
scene?.rootNode.childNodes[childCount].removeAnimationForKey(key as! String)
scene?.rootNode.childNodes[childCount].addAnimation(animation, forKey: key as! String)
}
}
childCount++
}
}
sceneView.scene = scene
sceneView.autoenablesDefaultLighting = true
}
if anybody can explain that would be great!
Ah, but there's another problem!
Here's the start frame of the animation:
and here's the end frame where we want to end up:
But at the end of the animation the scene jumps back to the start view.
I have 'fixed' this by amending the animation so that frame 1 is copy of the final frame. This works and isn't noticeable but doesn't seem a very elegant solution.
For the animation jumping back to the first frame, the isAppliedOnCompletion value is what you are looking for.
animation.repeatCount = 1
animation.isAppliedOnCompletion = true
This will make sure that the animation pauses on the final frame.
I know this is an old question, but I came across this same problem and found a solution for the jumping back to the beginning issue. If you set the animation to not be removed on completion, the object should stay at the end location:
if let animation = child.animationForKey(child.animationKeys.first!) {
animation.repeatCount = 1
animation.removedOnCompletion = false
...
This works for me. It's based off your answer but will go through the node's entire tree and limit all of their animation counts to one.
Personally I found that if I missed any of the descendant nodes when manually traversing and setting the node animation counts to one, I would have a problem. This ensures that the node passed in itself, and all child nodes will only animate once, and then hold the model in place after finishing.
Use like this animateEntireNodeTreeOnce(mostRootNode: nodeYouImportedFromCollada).
func animateEntireNodeTreeOnce(mostRootNode node: SCNNode){
onlyAnimateThisNodeOnce(node)
for childNode in node.childNodes {
animateEntireNodeTreeOnce(mostRootNode: childNode)
}
}
func onlyAnimateThisNodeOnce(_ node: SCNNode) {
if node.animationKeys.count > 0 {
for key in node.animationKeys {
let animation = node.animation(forKey: key)!
animation.repeatCount = 1
animation.isRemovedOnCompletion = false
node.removeAllAnimations()
node.addAnimation(animation, forKey: key)
}
}
}
I Agree with #Phil Dudas and I like to add also this workaround to Prevent The Animation from Start By Default By Reducing Speed to Zero, When you set Speed to Zero it will remain at First state,
nodeAnimation.speed = 0
animation.repeatCount = 1
nodeAnimation.animation.isRemovedOnCompletion = false
Related
I'm making a game in godot and have to store the animation position because the animation gets suspended by another one. I want to continue the animation where it was before and that's why I have to store the animation position and then set it to the stored value.
I've tried setting it (didn't work) and in the documentation and other places in the internet I haven't found anything helpful.
This is the script on it:
extends KinematicBody2D
onready var animation_player = $AnimationPlayer
var hurt_anim_playing: bool = false
var hurt_anim_progress: float = 0
func _ready():
animation_player.play("idle")
pass
func _physics_process(delta):
# for each touching heart, get hurt
for body in hitbox.get_overlapping_bodies():
if body.has_method("heart"):
G.health -= 1
hurt_anim_playing = true
hurt_anim_progress = animation_player.current_animation_position
animation_player.play("hurt")
update_sprite()
body.queue_free()
func die():
dieLayer.visible = true
get_tree().paused = true
func update_sprite():
sprite.frame = G.max_health - G.health
if G.health == 0:
die()
func _on_AnimationPlayer_animation_finished(anim_name):
if anim_name == "hurt":
hurt_anim_playing = false
animation_player.play("idle")
animation_player.current_animation_position = hurt_anim_progress
Actually I wanted to set the animation position and let the animation continue where it stopped, but instead I got an error
The problem is that current_animation_position has only a getter, not a setter:
https://docs.godotengine.org/en/3.1/classes/class_animationplayer.html#class-animationplayer-property-current-animation-position
To set the animation to a specific point, you can use advance(float delta), if you want to handle everything between start and the resuming point or seek(float seconds, bool update=false), if you just want to jump to the new position. You may test out, if you need to set update to true. The documentation says "If update is true, the animation updates too, otherwise it updates at process time."
Your code would simply look like this:
func _physics_process(delta):
# for each touching heart, get hurt
for body in hitbox.get_overlapping_bodies():
if body.has_method("heart"):
G.health -= 1
hurt_anim_playing = true
hurt_anim_progress = animation_player.current_animation_position
animation_player.play("hurt")
update_sprite()
body.queue_free()
func _on_AnimationPlayer_animation_finished(anim_name):
if anim_name == "hurt":
hurt_anim_playing = false
animation_player.play("idle")
animation_player.seek(hurt_anim_progress) #maybe (hurt_anim_progress, true)
I have a small test project that I'm trying to import into my production project. The ViewController that is causing the problem consists of a back ground image and a Scroll View (SV).
3 images appear in the test SV, yet only 2 appear in production. There appears to be a gap where the first image should appear.
Please note. The first image is the background image for the VC. I set it, then delete it from the array that feeds the scrollview.
Here are the two ViewControllers. Please note I embedded the VC in a TabBar and NavBar controller in test because that is what I have int production.
What is most puzzling is the code is exactly the same. The image URL's are the same. But the number of UIImageViews added to the scrollView are different. Note the last print statement in the code:
func setupList() {
print(foodPairings.count)
let imageStringURL = foodPairings[0].imageURL
let encodedURL = imageStringURL.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
guard let imageURL: URL = URL(string: encodedURL!) else {return}
bgImage.af_setImage(withURL: imageURL)
foodPairings.removeFirst()
print(foodPairings.count)
print(foodPairings.indices)
for i in foodPairings.indices {
let imageView = UIImageView()
let imageStringURL = foodPairings[i].imageURL
let encodedURL = imageStringURL.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
guard let postURL: URL = URL(string: encodedURL!) else {return}
imageView.af_setImage(withURL: postURL, placeholderImage: #imageLiteral(resourceName: "Placeholder"), filter: nil, progress: nil, imageTransition: .noTransition, runImageTransitionIfCached: false, completion: nil)
imageView.tag = i
imageView.contentMode = .scaleAspectFill
imageView.isUserInteractionEnabled = true
imageView.layer.cornerRadius = 20.0
imageView.layer.masksToBounds = true
listView.addSubview(imageView)
//attach tap detector
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapImageView)))
}
print(listView.subviews.count)
listView.backgroundColor = UIColor.clear
positionListItems()
}
The print statements in Test result in:
4 3
0..<3 4
Production prints the following:
4 3
0..<3 5
Why is listView.subviews.count different in production?
I have resolved this, but it is not clear what the source of the issue was.
In Test, my Scroll View had one subview even prior to me adding the array of UIImageViews. In Production, the Scroll View had two subviews prior to me adding the images in the array.
Just prior to the loop where I add my subviews, I remove all subviews from the ScrollView:
listView.subviews.forEach({ $0.removeFromSuperview() })
for i in foodPairings.indices {
print("SubviewCount: \(listView.subviews.count)")
let imageView = UIImageView()
...
Both my Test and Production macs are running XCode 9 Swift 4. Still remains a mystery why subview count was different.
Under the SKSpriteNode class, you can do the following to animate an object
private func animate(){
var playerTextures:[SKTexture] = []
for i in 1...3 {
playerTextures.append(SKTexture(imageNamed: "image00\(i)"))
}
let playerAnimation = SKAction.repeatActionForever(
SKAction.animateWithTextures(playerTextures, timePerFrame: 0.1))
self.runAction(playerAnimation)
}
The above code can animate an object using the sequence of images. Here the image files would be image001.png image002.png image003.png
Here come's my question, how can I animate images if the file names are
image001.png
image002.png
...
image009.png
image010.png
image011.png
image012.png
The key point here is the problem with the zero paddings. Any ideas?
Assuming you will only have three digits number you could add your pictures that way:
for i in 1...3 {
let imageNumber = String(format: "%03d", i)
playerTextures.append(SKTexture(imageNamed: "image\(imageNumber)"))
}
This will give you image001, image002 and image003
This requires that you import Foundation at the beginning of your swift file
I do a growth animation of a fixed number of items, and after growth, i moved it to left.
Make growth by apply matrix
var trans_vector = new THREE.Matrix4().makeTranslation(0, height / 2, 0);
var graphics = new Graphics();
var rectangle = graphics.box(width, height, material);
rectangle.geometry.applyMatrix(trans_vector);
When a new item is added, i remove one from the container that will be added to scene
var children = this.container.children;
if (this.current_number === this.max_number) {
this.container.remove(children[0]);
this.current_number = this.max_number - 1;
}
object.position.copy(this.position); // this is a fixed position
this.container.add(object);
this.current_number++;
I write a function to translate to left, using tweenjs (sole)
animateTranslation : function(object, padding, duration) {
var new_x = object.position.x - padding; // Move to left
console.log(new_x); // Duplicated item here :(
new TWEEN.Tween(object.position).to({
x : new_x
}, duration).start();
},
And I remove all the "previous" items, using for loop
for (var i = 0; i < this.current_number-1; i++) {
this.animateTranslation(this.container.children[i],
this.padding,
this.duration/4)
}
The above code run correctly if we open and keep this current tab.
The problem is when we move to another tab, do something and then move back, some objects have the same position, that cause the translation to the same position. It looks weird.
It appears on both Chrome, Firefox and IE11.
I dont know why, please point me out what happened.
Most modern browsers choose to limit the delay in setInterval and pause requestAnimationFrame in inactive tabs. This is done in order to preserve CPU cycles and to reduce power consumption, especially important for mobile devices. You can find more details about each browser in this answer
That means, while the tab is inactive, your tween animation is not working the way it is normally expected to.
A simple solution would be to halt the main animation loop if the tab is inactive using a variable.
window.onfocus = function () {
isActive = true;
};
window.onblur = function () {
isActive = false;
};
In order to make a pause in a SpriteKit game I made a pause button. It worker like a charm when I wanted to make an another scene for pause and respond to touch was transitioning to a scene. My function then looked like this (P.S. pause = pause button) But there were other problems with it and I decided to make pause within my main scene: playscene
So I added a pauseBackground and resumeButton that is attached to pause background and hided it (declared resumeButton.hidden = true)
Now my function looks like this:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if self.onGround {
self.speedY = -20.0
self.onGround = false
}
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.pause {
self.scene?.view?.paused = true
self.pauseBackground.hidden = false
self.resumeButton.hidden = false
if self.nodeAtPoint(location) == self.resumeButton {
self.pauseBackground.hidden = true
self.resumeButton.hidden = true
self.scene?.view?.paused = false
}
}
}
}
It's interesting because it worked with scene transitions, but now Xcode can't detect or ignore my tap in pause button location. I don't really know why. Could you please help me?
Update: I tried switch statement:
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
switch self.nodeAtPoint(location) {
case self.pause:
self.scene?.view?.paused = true
self.pauseBackground.hidden = false
self.resumeButton.hidden = false
case self.resumeButton:
self.pauseBackground.hidden = true
self.resumeButton.hidden = true
self.scene?.view?.paused = false
default:
println()
}
}
Sadly, it's not working either! I really have no idea why it's not detecting a touch in that location.
Give a name to your pause button. Control if your pause button is touched in touchesBegan by printing the name of the touched node.
Control the zPosition of the touched node and the pause button. Set the zPosition of the pause button = 1000 and try touching it.
EDIT:
Let's say, the node node1 is the parent node of the pauseButton.
node1.zPosition = 100.0f;
pauseButton.zPosition = 200.0f;
the continueButton is above the scene
continueButton.zPosition = 250.0f;
That means, that the zPosition of the pauseButton is 200 above the parent node node1. The zPosition of the continueButton (250) is less than the zPosition of the pauseButton above the scene, although the zPosition seems to be less (200). That's because the zPosition of the pauseButton is 300 above the scene. The zPosition of the parent node is very important to control the zPositions of its children and the other nodes of the scene.
zPosition of a node is always relative to its parent node. Have your both buttons (pause and resume button) the same parent node? The best way to control the touched node, is to give each node a name and a zPosition, and to print this (name and zPosition with NSLog() / println()) in the touchesBegan. With this you know exactly which node is touched and you know its zPosition. And so you can correct the zPosition of each node, so that it works as you need.