vitaliy
February 7, 2019, 9:13pm
#1
Hello!
A simple animation component:
var AnimateFrames = pc.createScript('animateFrames');
AnimateFrames.attributes.add("leftFrameEntity", {type: "entity", title: "Left Frame Animation"});
AnimateFrames.attributes.add("rightFrameEntity", {type: "entity", title: "Right Frame Animation"});
// initialize code called once per entity
AnimateFrames.prototype.initialize = function() {
};
// update code called every frame
AnimateFrames.prototype.update = function(dt) {
this.app.on("animate:frames", function () {
this.animate();
}, this);
};
AnimateFrames.prototype.animate = function () {
var leftFrameAnimation = this.leftFrameEntity.script.leftFrame;
leftFrameAnimation.startAnimation();
var rightFrameAnimation = this.rightFrameEntity.script.rightFrame;
rightFrameAnimation.startAnimation();
};
Which I have attached to an external html file
<button onclick="startAni()">Click me</button>
<script>
var app = pc.Application.getApplication();
app.on("start", function (t) {
console.log("started");
});
function startAni() {
app.fire("animate:frames");
}
</script>
However, the animation starts to work only after 3-5 clicks. What am I doing wrong?
Thanks!
yaustar
February 7, 2019, 9:52pm
#2
At the moment, you are registering an event listener every update frame. Move the listener to the initialize function and see if that helps?
// initialize code called once per entity
AnimateFrames.prototype.initialize = function() {
this.app.on("animate:frames", function () {
this.animate();
}, this);
};
If this doesn’t work, can you post a link to your project please?
vitaliy
February 8, 2019, 4:16pm
#3
I have tried it having in both, initialize and update, but that didn’t help.
https://playcanvas.com/editor/scene/704412
I have added an event to the example above to activate on left mouse click (see scripts/animate-frames.js) and even with that it activates after 3-5 clicks.
yaustar
February 8, 2019, 4:41pm
#4
Your problem is in the LeftFrame and RightFrame scripts
LeftFrame.prototype.startAnimation = function () {
if (this.time > this.duration) {
this.time = 0;
this.startPosition.copy(this.entity.getPosition());
this.targetPosition.copy(this.entity.getPosition());
this.targetPosition.x = this.startPosition.x < 0 ? 0 : -0.3;
}
};
Until 4 seconds have passed since the start of the app, the start and target positions never get copied since time is initialised to 0.
Here’s a fixed version: https://playcanvas.com/editor/scene/708036
I also made some changes to AnimateFrames on where the event listeners should be created.
1 Like
vitaliy
February 8, 2019, 6:08pm
#5
Thanks! As always, the solution is in the smallest detail