I'm developing a Fez-based HTML5 Canvas game using EaselJS and I've found a problem, that I can't solve myself, while trying to implement SpriteSheets to the hero.
The problem is that I've defined three animations to my hero ("stand", "jump" and "run") and when I try to change from one animation to another using hero.gotoAndPlay("run") or hero.gotoAndStop("stand") the animations don't change, change but show the first frame only or change to the wrong animation.
Can someone help me? What I'm doing wrong and how can I fix it? Thanks.
Here's the relevant JavaScript code I'm using to create the hero Sprite:
var data = {
images: ["http://i.imgur.com/M0GmFnz.png"],
frames: {width:34, height:46},
animations: {
stand:0,
run:[0,12,true,0.25],
jump:13
}
};
var spriteSheet = new createjs.SpriteSheet(data);
var hero = new createjs.Sprite(spriteSheet, "stand");
hero.offset = 4 + 1; // "+1" is important, change the first number only.
hero.regX = hero.offset + 2;
hero.regY = hero.offset;
hero.width = 34 - (hero.offset*2) - 12;
hero.height = 46 - (hero.offset*2);
hero.x = 0;
hero.y = 0;
hero.jumping = true;
stage.addChild(hero);
And the code I'm using to change the animation:
if(!left && !right){ // User isn't pressing left arrow or right arrow
hero.gotoAndStop("stand");
}else{
hero.gotoAndPlay("run");
}
JSFiddle
Official Site
If you are calling gotoAndStop or gotoAndPlay in a tick (or similar) then it will constantly reset to the first frame. You have to ensure you only call these functions one time when the animation changes.
A good way to set this up is to store the current animation, store it, and only change it up if the animation changes. Something like:
var animation;
if(!left && !right){ // User isn't pressing left arrow or right arrow
animation = "stand";
}else{
animation = "run";
}
if (currentAnimation != animation) {
hero.gotoAndStop(animation);
}
This is just an example, but should give you an idea. You should only call these methods one time to kick off an animation.
Related
I'm running into a bit of an odd issue with Paper.js - I'm using the library to scale the "petals" of a randomly generated flower while audio plays.
The issue crops up if the flower is "growing" and the user navigates to a different tab in the browser. Even though it appears that the onFrame event is not firing when the window is out of view, whichever petal is currently scaling at the time will continue to scale indefinitely.
I even tried using a special js library to determine if the window is in view and still wasn't able to get the petals to stop scaling.
You can view a demo here, as I was not even able to replicate this in a Paper sketch: https://demos2.paperbeatsscissors.com/
Also including my onFrame code here in case the problem is obvious to someone:
view.onFrame = function(event) {
// See if something is playing
if (playing > -1) {
// Get the active flower
var activeFlower = garden[playing],
activeData = activeFlower.data;
// Active layer and petal
var activeLayer = getEl(activeFlower, activeData.lIndex),
activePetal = getEl(activeLayer, activeData.pIndex);
// Variables
var time = activeData.audio.seek(),
scaleAmount = (1 / (activeData.timing / event.delta.toFixed(3))) * 2;
// Petal progression
if (!activeData.completed) {
if (activePetal.scaling.x < 1 && activePetal.scaling.y < 1) {
activePetal.pivot = {x: 0, y: activePetal.height / 2};
activePetal.scaling.x = activePetal.scaling.x + scaleAmount;
activePetal.scaling.y = activePetal.scaling.y + scaleAmount;
} else {
if (activeData.pIndex < (activeLayer.children.length - 1)) {
// If the petal is scaled, jump to a new petal
activeData.pIndex += 1;
} else {
if (activeData.lIndex > 0) {
// When all petals are bloomed, jump to a new layer
activeData.pIndex = 0;
activeData.lIndex -= 1;
} else {
// Set the flower as completed
activeData.completed = true;
}
}
}
}
activeFlower.rotate(.125, activeData.center);
// Reset the playing variable if the audio clip is complete and the flower has completed
if (!activeData.audio.playing() && time === 0 && activeData.completed) {
playing = -1;
}
}
}
Really stumped on this one so any help is greatly appreciated!
I think that your problem is coming from the fact that you base your scaling calculation on event.delta which represents the time elapsed since the last event fired.
The thing is that, if I'm not mistaken, under the hood, Paper.js onFrame event relies on requestAnimationFrame which does not fire when the tab if inactive.
So when you switch tab, wait for a while and get back to your tab event.delta value is big and your scaling value too, hence the size of your petals. This basic sketch showcase this behavior.
So in my opinion, you should simply check event.delta value and limit it if it's too high.
I have a drawButtons function that takes an argument of "nonhover", "hover1" or "hover2" and draws up a new button set to the canvas, and depending on the argument it takes, will draw the buttons different colors. It does work when i call it from setUpGame() but not when I call it from draw(). I want to call it from draw() because draw() is called 80 times a second in setInterval(). That way it can keep checking if the mouse is hovering over the button and draw the appropriate button set.
setUpGame() is called outside of any object or function. draw() is called by setInterval() which is outside of any function or object. setInterval calls draw 80 times a second.
getMouseOver() another function that is the one that should actually be called by draw(), because it says "if mouse is over button one: drawButtons("hover1") and so on. It just doesn't draw the buttons when I call it.
There are no errors in the browser Javascript console. I am using Chrome which works best with my game.
From this we can deduce that there is no problem with drawButtons() as it worked when called from setUpGame().
There is possibly a problem with draw() as drawButtons() doesn't work when I call it from there (but to perplex us more, displayNumbers does display the numbers when I call it from there) and it worked fine when playing the game (here we are not playing the game, we are on a start screen).
There is probably a problem with getMouseOver() because that doesn't work anywhere.
I will show you getMouseOver() for now. My program is getting big and it is overwhelming to show too much right from the start. I intend for this function to be called 80 times a second.
getMouseOver: function() {
window.onload = (function(){
window.onmouseover = function(e) {
// IE doesn't always have e here
e = e || window.event;
// get event location
// change the code so that it gives the relative location
var location = {
x: e.pageX - offset.x,
y: e.pageY - offset.y
};
if (location.x > 103.5 && location.x < 265.5) {
if (location.y > 240 && location.y < 291) {
nonGameContent.drawButtons("hover1");
}
}
if (location.x > 103.5 && location.x < 265.5) {
if (location.y > 160 && location.y < 212) {
nonGameContent.drawButtons("hover2");
}
}
else{
nonGameContent.drawButtons("nonHover");
}
}
})},
In this fiddle you have click() and onmousemove() that are working.
I didn't understand well if you want to display button at the beginning or just when the mouse hovers somewhere on the future place of the button but it's a beginning :
http://jsfiddle.net/Akinaru/3a7g2/57/
Main modification :
canvas.onmousedown = nonGameContent.getMouseClick;
canvas.onmousemove = nonGameContent.getMouseOver;
to change the canvas rectangle color when you mouse over it use onmousemove to find if you are over it, then redraw the canvas with a different color rectangle
getMouseClick: function() {
window.onmousemove = function(e) {
I am developing a simple HTML5 game presently which you can play test at the following URL:
http://frankcaron.com/simplegame/game.html
The code is here:
https://github.com/frankcaron/Personal_HTML5_GamePrototype/blob/master/js/game.js
In order to animate elements, I'm using a few setIntervals. The main game loop has a setInterval which works fine. Some fading elements use them, as well, without issue. The one I'm having an issue with is one for an on-click animation.
The issue I'm having is that, in Safari and also to some extent in Chrome, the click event and animation is not responsive. It doesn't fire every time. I think there is some conflict with the concurrent intervals running. I'm not sure why.
I've done some research on the other method of HTML5 animation using requestAnimFrame but I don't think that'll solve my problem here.
Here is the code of interest:
//Track mousedown
addEventListener('mousedown', function (e) {
//Safari Fix
e.preventDefault();
//If you click while the game is going, do your special move
performSpecial();
}
//Perform a special move
var performSpecial = function () {
switch(classType)
{
case 1:
//Class 1
break;
default:
//No class
renderExplosion();
}
}
//Render explosion special move
var renderExplosion = function () {
//Temp vars
var alpha = 1.0; // full opacity
var circleMaxRadius = 32;
fadeCircle = setInterval(function () {
ctx.beginPath();
ctx.arc(hero.x + 16, hero.y + 16, circleMaxRadius, 0, 2 * Math.PI, false);
ctx.lineWidth = 5;
ctx.strokeStyle = "rgba(255, 0, 0, " + alpha + ")";
ctx.stroke();
circleMaxRadius = circleMaxRadius + 5;
alpha = alpha - 0.05 ; // decrease opacity (fade out)
if (alpha < 0) {
clearInterval(fadeCircle);
}
}, 1);
};
Welp, I rewrote the application using window.requestAnimationFrame and I no longer have this problem. The code is up on my Github if anyone wants to see the full solution.
In brief, I removed all of the intervals and replaced the entire game loop. When an animation effect is needed, I turn a flag on corresponding with the event. The renderer checks this conditional and renders the effect if the flag is on, turning the flag off again when it's done.
I had an idea for like a bus window as a fixed frame, about 800px wide, with a parallax city with the content on billboards spaced out so when you scroll between them it allows the parallax to look like bus is moving. The content will be much bigger than the window like a sprite and I'll put forward and back buttons that will scrollBy (x amount, 0). I have a working parallax script and a rough cityscape of 3 layers that all work fine.
I have hit a wall. I am trying to clear a scrollBy animation after it scrolls 1000px. Then you click it again and it goes another 1000px. This is my function.
function scrollForward() {
window.scrollBy(5,0);
scrollLoop = setInterval('scrollForward()',10);
}
So far I can only clear it when it gets to 1000. I tried doing 1000 || 2000 ect but after the first one it goes really fast and won't clear.
Excelsior https://stackoverflow.com/users/66580/majid-fouladpour wrote a great piece of code for someone else with a different question. It wasn't quite right for what the other guy wanted but it is perfect for me.
function scrollForward() {
var scrolledSoFar = 0;
var scrollStep = 75;
var scrollEnd = 1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar >= scrollEnd ) clearInterval(timerID);
}, 10);
}
function scrollBack() {
var scrolledSoFar = 0;
var scrollStep = -75;
var scrollEnd = -1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar <= scrollEnd ) clearInterval(timerID);
}, 10);
}
Now for step two figuring out how to put this content animation behind a frame.
Not quite sure what your asking here. Perhaps you could provide more relevant code?
I do see a potential issue with your code. You call setInterval('scrollForward()', 10) which will cause scrollForward to be called every 10ms. However, each of those calls to scrollForward will create more intervals to scrollForward creating a sort of explosion of recursion. You probably want to use setTimeout or create your interval outside of this function.
Also, as an aside you can change your code to simply: setInterval(scrollForward, 10). Removing the quotes and the parens makes it a littler easier to read and manager. You can even put complex, lambda functions like:
setInterval(function() {
scrollForward();
// do something else
}, 10);
edit:
So if you know that scrollForward moves the item 10px, and you want it to stop after it moves the item 1000px, then you simply need to stop it has moved that much. I still don't know how your code is actually structured, but it might look something like the following:
(function() {
var moved_by = 0;
var interval = null;
var scrollForward = function() {
// move by 10px
moved_by += 10;
if (moved_by === 1000 && interval !== null) {
clearInterval(interval);
}
};
var interval = setInterval(scrollForward, 10);
})();
If you want to clear it after 1000 or 2000, you simply adjust the if statement accordingly. I hope that helps.
I am trying to create a sort of slideshow animation. I have the codes here: jsFiddle.
These tablets would rotate around.
The problem is that, at random times, the animation will move out of line. The wrong tablets undergo wrong animations. Here are the screenshots:
And this is how it looks like when the animations goes wrong
The main problem is I don't understand why the animation would go wrong random times. In my computer it will run properly for hours, but in other cases (especially on Safari).
You could store the expected final css values for each animated el and then in the animate callback set these values, so for each animated el something like
var el = $(selector);
el.data("finalCSS", { your expected final CSS values })
$("selector").animate({animation properties}, function() {
el.css(el.data("finalCSS")).data("finalCSS", undefined);
})
This doesn't help with figuring out why it's happening (but I can't recreate the issue myself), but provides a failsafe to make sure the layout doesn't break;
I believe this happens when you try to animate before the previous animation has ended. Use jQuery stop() just before you animate. For example:
$('#animatingDiv').stop(false, true).animate({height:300}, 200, callback);
The first param(false) will empty the animation queue on that element and the second param(true) will jumps to the end of current animation before starting a new animation.
You can do this with far less code and far fewer headaches.
1. Store your tablet position attributes in classes
.tablet1{
height:100px;
width:140px;
margin-left:-540px;
top: 200px;
z-index:10;
}
2. Use a general function to handle all your transitions.
JQuery UI will do all the work for you if you use switchClass
switchTabletsRight = function(){
var i, next, max = 5;
for(i = 1; i <= max; i++){
next = (i < max)? i + 1 : 1;
$(".tablet" + i).switchClass("tablet" + i, "tablet" + next);
}
};
Here's the JSfiddle proof of concept: http://jsfiddle.net/nRHag/4/
You are setting CSS positions to decimal values.
img_w = $("#tablet"+num+" img").width();
img_w = img_w *140 / 600;
img_h = $("#tablet"+num+" img").height();
img_h = img_h *140 /600;
...
var new_width = $(this).width() * 140 / 600;
$(this).css('width', new_width);
var new_height = $(this).height() * 140 / 600;
$(this).css('height', new_height);
Your division could be cause decimal results which have different effects in different browsers. Sub pixel CSS positioning may be creating your unintended errors.