How to disable code execution until tween complete? - javascript

Hi guys i am using Phaser 3.5 and wanted to stop this click function from executing if the tween is still ongoing?
game.input.on("pointerdown", function(pointer) {
game.tweens.add({
targets: playerHands,
angle: 20,
duration: 1000,
yoyo: true
});
});
Thank you

A flag variable would be something like:
game.canTweenFlag = true;
game.input.on("pointerdown", function(pointer) {
if(game.canTweenFlag) {
game.canTweenFlag = false;
game.tweens.add({
targets: playerHands,
angle: 20,
duration: 1000,
yoyo: true,
onComplete: function () { game.canTweenFlag = true; }
});
}
});

Related

Phaser 3 - Particles become more the more often I emit them?

I have particles that I emit when clicking and moving my mouse over a certain object. However I noticed that while the particles start out as little, they become more and more the more often I click and move my mouse,until the stream of particles is far too dense.
This only seems to happen when I click down multiple times (thus triggering the pointerdown event multiple times), not when I click once and keep moving.
How can I stop this?
function pet(start, scene, pointer = null)
{
if(start){
scene.input.on('pointermove', function(){
if (scene.input.activePointer.isDown && gameState.chara.getBounds().contains(scene.input.activePointer.x, scene.input.activePointer.y)){
gameState.sparkle.emitParticle(1,scene.input.activePointer.x, scene.input.activePointer.y); // !!!! Here is where I emit my particles
}
});
} else {
gameState.sparkle.stop(); // !!!! Here I stop my particles
}
}
const gameState = {
gameWidth: 800,
gameHeight: 800,
menu: {},
textStyle: {
fontFamily: "'Comic Sans MS'",
fill: "#fff",
align: "center",
boundsAlignH: "left",
boundsAlignV: "top"
},
};
function preload()
{
this.load.baseURL = 'assets/';
// Chara
this.load.atlas('chara', 'chara.png', 'chara.json');
// Particle
this.load.image('sparkle', 'sparkle.png'); // Here I load my particle image
}
function create()
{
// Scene
let scene = this;
// Chara
this.anims.create({
key: "wag",
frameRate: 12,
frames: this.anims.generateFrameNames("chara", {
prefix: 'idle_000',
start: 0,
end: 5}),
repeat: 0,
});
this.anims.create({
key: "happy",
frameRate: 12,
frames: this.anims.generateFrameNames("chara", {
prefix: 'happy_000',
start: 0,
end: 5}),
repeat: -1
});
gameState.chara = this.add.sprite(400, 400, "chara", "idle_0000");
gameState.chara.setInteractive({cursor: "pointer"});
// !!!! Here I set up my Particle Emitter !!!!
gameState.sparkle = this.add.particles('sparkle').createEmitter({
x: gameState.height/2,
y: gameState.width/2,
scale: { min: 0.1, max: 0.5 },
speed: { min: -100, max: 100 },
quantity: 0.1,
frequency: 1,
lifespan: 1000,
gravityY: 100,
on: false,
});
gameState.chara.on('pointerdown', function(){ pet(true, scene) });
gameState.chara.on('pointerout', function(){ pet(false, scene, 'default') });
gameState.chara.on('pointerup', function(){ pet(false, scene, 'pointer') });
}
function update()
{
}
// Configs
var config = {
backgroundColor: "0xf0f0f0",
scale: {
width: gameState.gameWidth,
height: gameState.gameHeight,
autoCenter: Phaser.Scale.CENTER_BOTH
},
scene: {
preload, create, update
}
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
The problem is, that you are adding a new scene.input.on('pointermove',...) event-handler in the pet function, on each click.
I would only change the code abit (look below), this should prevent generating too many particles and too many event-handlers (too many event-handlers could harm performance, so be careful, when adding them).
Here is how I would modify the Code:
(I stripped out and added some stuff to make the demo, easier to understand and shorter. And also that the snippet can be executed, without errors/warnings)
The main changes are marked and explained in the code, with comments
function pet(start, scene, pointer = null)
{
if(start){
// Update: remove Event listener add click state
gameState.mouseDown = true
} else {
// Update: add click state
gameState.mouseDown = false;
gameState.sparkle.stop();
}
}
const gameState = {
gameWidth: 400,
gameHeight: 200,
// Update: add click state
mouseDown: false
};
function create()
{
// Scene
let scene = this;
// Just could for Demo START
var graphics = this.add.graphics();
graphics.fillStyle(0xff0000);
graphics.fillRect(2,2,10,10);
graphics.generateTexture('particle', 20, 20);
graphics.clear();
graphics.fillStyle(0xffffff);
graphics.fillRect(0,0,40,40);
graphics.generateTexture('player', 40, 40);
graphics.destroy();
// Just Code for Demo END
gameState.chara = this.add.sprite(200, 100, "player");
gameState.chara.setInteractive({cursor: "pointer"});
gameState.sparkle = this.add.particles('particle').createEmitter({
scale: { min: 0.1, max: 0.5 },
speed: { min: -100, max: 100 },
quantity: 0.1,
frequency: 1,
lifespan: 1000,
gravityY: 100,
on: false,
});
gameState.chara.on('pointerdown', function(){ pet(true, scene) });
gameState.chara.on('pointerout', function(){ pet(false, scene, 'default') });
gameState.chara.on('pointerup', function(){ pet(false, scene, 'pointer') });
// Update: add new single Event Listener
gameState.chara.on('pointermove', function(pointer){
if(gameState.mouseDown){
gameState.sparkle.emitParticle(1,pointer.x, pointer.y);
}
});
}
// Configs
var config = {
width: gameState.gameWidth,
height: gameState.gameHeight,
scene: { create }
};
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

How to scroll new page to top on load on click?

I'm using barba.js to fade new pages in. Code must be placed between the barba wrapper div. When I click a link to a new page though, the new page fades in at the same position as the previous page was in. So if the user clicks a link, the new page is loading in near , which I don't want.
How can I get the new page to load in at the top?
I found the answer on stack about scrollRestoration function but I still don't understand how to make this work.
Could somebody help me to compile the js code below, add some css or html to fix this issue?
$(window).scrollTop(0);
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
function delay(n) {
n = n || 2000;
return new Promise((done) => {
setTimeout(() => {
done();
}, n);
});
}
function pageTransition() {
var tl = gsap.timeline();
tl.to(".animate-this", {
duration: .2, opacity: 0, delay: 0, y: 30, //scale:0, delay: 0.2,
});
tl.to(".animate-this", {
duration: 0, opacity: 0, delay: 0, scale:0, //scale:0, delay: 0.2,
});
tl.fromTo(".loading-screen", {width: 0, left: 0}, {
duration: 1,
width: "100%",
left: "0%",
ease: "expo.inOut",
delay: 0.3,
});
tl.to("#svg-1", {
duration: 1, opacity: 0, y: 30, stagger: 0.4, delay: 0.2,
});
tl.to(".loading-screen", {
duration: 1,
width: "100%",
left: "100%",
ease: "expo.inOut",
delay: 0, //CHANGE TIME HERE END TRANS
});
tl.set(".loading-screen", { left: "-100%", });
tl.set("#svg-1", { opacity: 1, y: 0 });
}
function contentAnimation() {
var tl = gsap.timeline();
tl.from(".animate-this", { duration: .5, y: 30, opacity: 0, stagger: 0.4, delay: 0.2 });
}
$(function () {
barba.init({
sync: true,
transitions: [
{
async leave(data) {
const done = this.async();
pageTransition();
await delay(2500);
done();
},
async enter(data) {
contentAnimation();
},
async once(data) {
contentAnimation();
},
},
],
});
});
Have a look:
https://pasteboard.co/Ja33erZ.gif
Here also a codepen to check my issue (html,css):
https://codepen.io/cat999/project/editor/AEeEdg
scrollRestoration shouldn't be necessary, this can be done by resetting scroll position during the transition:
tl.fromTo(".loading-screen", {width: 0, left: 0}, {
duration: 1,
width: "100%",
left: "0%",
ease: "expo.inOut",
delay: 0.3,
onComplete: function() {
window.scrollTo(0, 0);
}
});
Working example here: https://codepen.io/durchanek/project/editor/ZWOyjE
This should be what you're looking for:
barba.hooks.enter(() => {
window.scrollTo(0, 0);
});
(can be found in the docs)

What is the best method of starting/ stoping js anime timeline on input

I'm attempting to create an animation (using anime.js) that plays an animation timeline once when the users starts typing and will loop for the duration that the user is typing in the input box. When the user stops typing the animation will complete its current loop and stop playing.
Here's my progress at the moment, you can observe the animation working incorrectly: https://codepen.io/andrewbentley/full/XqMrze
Here's what my anime.js code timeline:
var basicTimeline = anime.timeline({
loop: true,
autoplay: false,
duration: 700
});
basicTimeline
.add({
targets: '#circ1',
duration: 100,
translateY: -10,
easing: 'easeInQuad'
})
.add({
targets: '#circ1',
duration: 100,
translateY: 0,
easing: 'easeInQuad'
})
.add({
targets: '#circ2',
duration: 100,
translateY: -10,
easing: 'easeInQuad'
})
.add({
targets: '#circ2',
duration: 100,
translateY: 0,
easing: 'easeInQuad'
})
.add({
targets: '#circ3',
duration: 100,
translateY: -10,
easing: 'easeInQuad'
})
.add({
targets: '#circ3',
duration: 100,
translateY: 0,
easing: 'easeInQuad'
})
.add({
targets: '#circ3',
delay: 100
});
document.querySelector('#email').onkeypress = basicTimeline.play;
document.querySelector('#email').onkeyup = basicTimeline.pause;
Is anyone able to advise me as to the best way of achieving the desired effect whilst using anime.js timeline utility and the use of event listeners such as onkeypress, onkeyup etc.
I think you need a timer which pauses your animation after some time of inactivity.
https://codepen.io/anon/pen/qYoPKQ
var timer = false;
document.querySelector('#email').onkeypress = function () {
if(basicTimeline.paused) basicTimeline.play();
if(timer) clearTimeout(timer);
timer = setTimeout(function() {
basicTimeline.pause();
basicTimeline.reset();
}, 500);
};
The issue of stopping an animation at the end of the current loop has been raised here:
on github There are some good suggestions there.
Perhaps the best one is from Edrees Jalili
function pausableLoopAnime({loopComplete, ...options}) {
const instance = anime({
...options,
loop: true,
loopComplete: function(anim) {
if(instance.shouldPause) anim.pause();
if(typeof loopComplete === 'function') loopComplete(anim);
}
});
instance.pauseOnLoopComplete = () => instance.shouldPause = true;
return instance;
}
const animation= pausableLoopAnime({
targets: '.polymorph',
points: [
{ value: '215, 110 0, 110 0, 0 47.7, 0 67, 76' },
{ value: '215, 110 0, 110 0, 0 0, 0 67, 76' }
],
easing: 'easeOutQuad',
duration: 1200,
});
setTimeout(animation.pauseOnLoopComplete, 100)

GreenSock TimelineMax starting early

I have been trying to get the animation to fire off on click, I have created the animated via TimelineMax. I can't see why but it keeps firing off the first instance of this animation, there are 5 .blackout-panel and it plays the animation automatically for the first .blackout-panel, but I have no idea why - I want the full animation to be controlled by on click.
var showBarsTL = new TimelineMax({ paused: true, onComplete: killAnimation });
$('.portfolio-panel').on("click", function () {
showBarsTL.play()
});
showBarsTL.add (TweenMax.staggerTo(".blackout-panel", 0, {y:100+ '%', onStart: "", onStartParams:["{self}"], ease: Power1.easeInOut}, 0.1275, 0));
showBarsTL.add (TweenMax.from(".blackout-panel", 0, {css:{top:"auto", bottom:"0"}}));
showBarsTL.add (TweenMax.staggerTo(".blackout-panel", 0, {css:{height:"0", bottom:"0", top:"auto"}, delay: 0.1275, ease: Power1.easeInOut}, 0.1275));
function killAnimation() {
showBarsTL.clear();
}
I have created a codePen to demonstrate this: http://codepen.io/Tekkie/pen/XpBOYV/?editors=1010
Any guidance would be appreciated. Also my killAnimation function doesn't seem to be getting fired.
EDIT: 1 - I have resolved the pausing issue by putting a delay. My new JS is as follows:
var $blackoutPanels = $('.blackout-panel');
var showBarsTL = new TimelineMax({ paused: true });
showBarsTL
.add (TweenMax.staggerTo($blackoutPanels, **0.1275**, {y:100+ '%', onStart: "", onStartParams:["{self}"], ease: Power1.easeInOut}, 0.1275, 0))
.add (TweenMax.from($blackoutPanels, 0, {css:{top:"auto", bottom:"0"}}))
.add (TweenMax.staggerTo($blackoutPanels, 0, {css:{height:"0", bottom:"0", top:"auto"}, delay: 0.1275, ease: Power1.easeInOut}, 0.1275));
$('.portfolio-panel').on("click", function () {
showBarsTL.play();
});
EDIT: 2 - I have resolved all issues using the following JS:
var $blackoutPanels = $('.blackout-panel');
var showBarsTL = new TimelineMax({
paused: true
});
showBarsTL
.add(TweenMax.staggerFrom($blackoutPanels, 0, {
yPercent: -100,
top: -100 + "%",
onStartParams: ["{self}"],
ease: Power0.easeInOut
}, 0, 0))
.add(TweenMax.staggerTo($blackoutPanels, 0.3, {
yPercent: 0,
top: 0,
onStartParams: ["{self}"],
ease: Power1.easeInOut
}, 0.125, 0))
.add(TweenMax.to($blackoutPanels, 3, {
yPercent: +100,
top: +100 + "%",
onStartParams: ["{self}"],
delay: 0.3,
ease: SlowMo.ease.config(0.4, 1, false)
}, 0.3, 0))
.add(TweenMax.to($blackoutPanels, 0, {
yPercent: -100,
top: -100 + "%",
delay: 0.375
}));
$('.portfolio-panel').on("click", function() {
showBarsTL.restart(false, false);
});
Try to set the pause like this:
var showBarsTL = new TimelineMax({onComplete: killAnimation }).paused(true);
and in your function:
$('.portfolio-panel').on("click", function () {
showBarsTL.paused(false);
});

Lof JSliderNews jQuery - how to pause on hover?

jQuery(function($) {
var buttons = {
previous: jQuery('#lofslidecontent45 .lof-previous'),
next: jQuery('#lofslidecontent45 .lof-next')
};
window.setTimeout(function(){
$obj = jQuery('#lofslidecontent45').lofJSidernews({
interval: 4000,
direction: 'opacitys',
easing: 'easeInOutExpo',
duration: 1200,
auto: true,
maxItemDisplay: 3,
navPosition: 'horizontal', // horizontal
navigatorHeight: 40,
navigatorWidth: 70,
mainWidth: 1000,
buttons: buttons,
isPreloaded:false
});
},500);
});
How to configure pause on hover?
is there any reference for this slider?
or is there any option like hover: stop?
there is no such config like hover: "stop".
But if you look in the actual .js file, you will find
$( obj ).hover(function(){
self.stop();
$buttonControl.addClass("action-start").removeClass("action-stop").addClass("hover-stop");
}, function(){
if( $buttonControl.hasClass("hover-stop") ){
if( self.settings.auto ){
$buttonControl.removeClass("action-start").removeClass("hover-stop").addClass("action-stop");
self.play( self.settings.interval,'next', true );
}
}
} );
That means, hover stop functionality is default there.

Categories