Craftyjs Sprite Animation issue - javascript

I'm currently trying to make a game with crafty js and I'm stuck with the sprite Animation.
I don't really know what I'm doing wrong ..
Here is the working code :
http://aaahdontpaintmeinred.me.pn/
Here is how I load the sprite in my loading scene :
Crafty.scene('Loading', function(){
// Draw some text for the player to see in case the file
// takes a noticeable amount of time to load
Crafty.e('2D, DOM, Text')
.text('Loading...')
.attr({ x: 0, y: Game.height()/2 - 24, w: Game.width() });
// Load our sprite map image
Crafty.load(['assets/mansprite.gif'], function(){
// Once the image is loaded...
// Define the individual sprites in the image
// Each one (spr_tree, etc.) becomes a component
// These components' names are prefixed with "spr_"
// to remind us that they simply cause the entity
// to be drawn with a certain sprite
Crafty.sprite(133, 'assets/mansprite.gif', {
mansprite:[0, 0]
});
// Now that our sprites are ready to draw, start the game
Crafty.scene('LevelEditor');
})
})
And here is how I try to bind and Animate in my player component :
Crafty.c('PlayerCharacter', {
init: function() {
this.requires('Actor, Collision,FPS,mansprite,SpriteAnimation,WiredHitBox')
.attr({maxValues:1,boost:false,trailSpacing:100,currentFrame:0})
.collision();
this.animate('run',0, 0, 3);
this.animate('idle',3, 0, 1);
this.requires('FluidControls')
//this.rotation+=90;
.onHit("FinishLine",this.endLevel)
.onHit("DeathWall",this.omagaDie)
.onHit("Booster",this.booster)
.bind("EnterFrame",function(fps){
if(this.move.up)
{
this.animate('run', 4,-1);
var spacing = this.trailSpacing;
if( this.currentFrame%((60*spacing)/1000) == 0)
Crafty.e("montexte").spawn(this.x,this.y,this.boost,this.xspeed,this.yspeed,this.rotation%360,this.h,this.w);
}else
{
if(!this.move.down)
{
this.animate('idle', 4,1);
}
}
this.currentFrame++;
if(this.currentFrame >=60)
this.currentFrame=0
})
;
},
Hope someone could point out what is going wrong !
If you need more details or you have questions, don't hesistate !
Thanks

Ok, so I solved the problem by using the 0.5.3 version.
Still don't know what's going on. But will try to give an answer here.

Use the non minified version.
I was using Crafty v0.5.4 minified and sprite animation was not working, no errors in console log.
Then after several hours of struggling I tried with the non minified version and the sprite animation started to work properly.

Related

PIXI.JS Newbie, looking for advice and troubleshoot of a textureCache, loader issue

ive ventured into the world of PIXI and JS, new programming language for me, liking the way it is right now but i have an issue.
I am a bit confused with the TextureCache and the loader. If you look at part of my code i try to add 3 different images to the screen. Ive been following the 'Get Started section' of the pixi website. I wanted to add their cat image, which i have, the tileset image (all of it)* and then a tile of the tileset image.
The issue is, i create 3 new sprite instances and the tileset image shows the area ive set for the tile(rocket) when i want it to show the whole tileset. Ive loaded in the tileset iin the cahce and the loader.
Why does tile show the cropped image and not the whole image?
Am i using the cache correctly to just store images?
Am i using the resources method properly to locate the image FROM the cache or the loader?
Is there any point of the cache?
my thoughts**
when you use the rectangle method, it destroys the original image and the cropped version is now tileset1 (the name of my image)?
<html>
<body>
<script src="pixi.js"></script>
<script>
//Aliases
let Application = PIXI.Application,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite,
Rectangle = PIXI.Rectangle,
TextureCache = PIXI.utils.TextureCache;
let app = new PIXI.Application({
width: 1000,
height: 600,
antialias: true,
transparent: false,
resolution: 1
}
);
//Add the canvas that Pixi automatically created for you to the HTML document
document.body.appendChild(app.view);
TextureCache["tileset1.png","images/3.png"];
//load an image and run the `setup` function when it's done
loader.add(["images/3.png","tileset1.png"]).load(setup);
//This `setup` function will run when the image has loaded
function setup() {
let texture = TextureCache["tileset1.png"];
let rectangle = new Rectangle(96,64,32,32);
texture.frame = rectangle;
//Create the cat sprite, use a texture from the loader
let card = new Sprite(resources["images/3.png"].texture);
let tile = new Sprite(resources["tileset1.png"].texture);
let rocket = new Sprite(texture);
card.scale.set(0.06,0.06);
tile.x=400;
tile.y=400;
rocket.x=100;
rocket.y=100;
//Add the cat to the stage
app.stage.addChild(card);
app.stage.addChild(tile);
app.stage.addChild(rocket);
app.renderer.render(app.stage);
}
</script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.2.4/pixi.js"></script>
Is there any point of the cache? - this question seems to be most important from your questions :)
Searching around about "pixi.js" and "TextureCache" gives following answers for example:
https://github.com/pixijs/pixi.js/issues/4053
MySecret commented on May 23, 2017:
the docs has no specs about PIXI.utils.TextureCache
...
englercj commented on May 26, 2017
This is intentional, it is not meant as a public-facing API. It is an internal cache used by some texture creation methods.
https://www.html5gamedevs.com/topic/17788-loader-and-texturecache-tutorial-anywhere/
xerver - Pixi.js Moderator:
Here is the loader: https://github.com/englercj/resource-loader
The code is really well documented, and there are examples on the readme. The pixi examples also use the loader a few times: http://pixijs.github.io/examples/
The TextureCache is an internal mechanism, there is rarely any reason you should even know it exists.
https://www.html5gamedevs.com/topic/25575-pixiloaderresources-or-texturecache/
xerver - Pixi.js Moderator:
Dont do this:
let e = PIXI.utils.TextureCache[player.img];
Instead use the resources the loader loaded for you:
let e = PIXI.loader.resources[player.img].texture;
...
TLDR: Usually TextureCache shouldnt be used directly :)
See also:
this explanation: https://www.html5gamedevs.com/topic/9255-pixijs-caching/?tab=comments#comment-55233
http://pixijs.download/release/docs/PIXI.BaseTexture.html#.addToCache
^ example of usage: https://jsfiddle.net/themoonrat/br35x20j/

EaselJs and TweenJs: Change image of Bitmap in tweening

I'm trying to create an animation with a flask image. I want to pour the flask, then replace the flask with an empty one, and then return the flask to its original location. The code I have right now looks like this:
var renderPour = function (flask, index){
// Using a Motion Guide
curX = flask.x;
curY = flask.y;
createjs.Tween.get(flask)
.wait(2000*index)
.to({x:100, y:90, rotation:-100}, 700, createjs.Ease.quadOut)
.to({image:'/assets/empty_flask'+(index+1)+'.svg'}, 0)
.to({x:curX, y:curY, rotation:0}, 700, createjs.Ease.quadOut);
}
According to the documentation, it says
Non-numeric properties will be set at the end of the specified duration.
So I expect the image src property to be changed. But when I run my code, the Bitmap just disappears and I have a 'invisible' Bitmap there. I know it's still there because I have an array that keeps track of all Bitmaps and it's still there, and I just can't see it. When I check the image's src value in the console, it's changed and correct.
I did some research and guessed that it's probably because the stage is not updated. Here is my update stage code:
createjs.Ticker.setFPS(60);
createjs.Ticker.on("tick", tick);
createjs.MotionGuidePlugin.install();
function tick(event) {
stage.update(event);
console.log('x: ', flaskArr[1].x, 'y', flaskArr[1].y);
}
And I tried to run stage.update() in the console as well, but the Bitmap is still invisible.
Additionally it seems that the later half of the animation is still working, except that the Bitmap is not showing according to the log.
I'm wondering is there a correct way to replace the image in TweenJs? Or is there another way to replace the image in the middle of the animation? Very much appreciated!
I figured out the solution on my own, so i'll just post it. I have to pass a new image instead of just a src string:
var emptImage = new Image();
emptImage.src = emptyFlaskPath(id);
createjs.Tween.get(flask)
.wait(2000*(flask.id-1))
.to({x:100, y:90, rotation:-100}, 700, createjs.Ease.quadOut)
.to({image: emptImage}, 0)
.to({x:curX, y:curY, rotation:0}, 700, createjs.Ease.quadOut);

Create js animation of a horizontal spritesheet

I have gone through the docs and sample only to be lost in outdated docs. Apparently there is no samples for the latest version of createjs.
I need to smooth scroll a horizontal spritesheet. So that the middle of images are shown before the new image is entirely in the "window". So the place in the page doesnt move only what is displayed from the single column horizontal spritesheet is different. And we do not switch between images we scroll up and down.
I am at my wits end with this.
this.sprite = new createjs.BitmapAnimation(spriteSheet);
that line gives an error
not a constructor
this.sprite = createjs.BitmapAnimation(spriteSheet);
gives an error
not a function
here is the sprite sheet
https://github.com/nydehi/asp.net-mvc-example-invoicing-app/blob/master/screenshots/1.png
i am doing this now and no error but nothing is displayed.
<script type="text/javascript" src="createjs-2014.12.12.min.js"></script>
<script>
function init() {
var data = {
images: ["1.png"],
frames: {width:15, height:20},
animations: {
stand:0,
run:[1,5],
jump:[6,8,"run"]
}
};
var spriteSheet = new createjs.SpriteSheet(data);
var animation = new createjs.Sprite(spriteSheet, "run");
var stage = new createjs.Stage("demoCanvas");
stage.addChild(animation);
animation.gotoAndPlay("run"); //walking from left to right
stage.update();
}
</script>
You're probably using a more recent version of CreateJS (around version 0.8.2) which no longer has a BitmapAnimation class on it.
Older versions (0.6.0) had it, but it was most likely replaced by the SpriteSheet class.
Check here for the most recent documentation.
The earlier comments about BitmapAnimation being deprecated long ago are right. Your updated code sample looks fine otherwise.
I think you are just missing something to update the stage when contents change. Your sample just has the one update, but because your image is loaded using a string path, it is not ready yet when you call stage.update().
Any time contents change, you need to tell the stage to refresh. Typically, this is manually controlled when contents change, or constantly using the Ticker.
createjs.Ticker.on("tick", function(event) {
// Other updates
// Update the stage
stage.update(event);
});
// Or a handy shortcut if you don't need to do anything else on tick:
createjs.Ticker.on("tick", stage);

How to reset its position back to the origin when it reach the end of frame?

This one of the phaser examples, what Im trying to do is to load the image again when it reach the end o the frame. Can somebody explain how to do this
var game = new Phaser.Game(1500, 200, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });
function preload() {
// You can fill the preloader with as many assets as your game requires
// Here we are loading an image. The first parameter is the unique
// string by which we'll identify the image later in our code.
// The second parameter is the URL of the image (relative)
game.load.image('Car', 'car.jpg');
}
function create() {
// This creates a simple sprite that is using our loaded image and
// displays it on-screen
// and assign it to a variable
var image = game.add.sprite(0, 0, 'Car');
game.physics.enable(image, Phaser.Physics.ARCADE);
image.body.velocity.x=750;
if (image>game.width)
{
game.load.image('Car', 'car.jpg');
var image = game.add.sprite(0, 0, 'Car');
}
}
I assume the above is just pseudo code because there are lots of little errors. But there are a number of issues with this approach.
If you know what the new image needs to be in advance, then preload it up front and then use loadTexture to apply it:
function preload() {
game.load.image('Car', 'car.jpg');
game.load.image('Pumpkin', 'pumpkin.png');
}
...
function update() {
if (car.x > game.width) {
car.loadTexture('Pumpkin');
}
}
Also some other things to watch out for:
1) Only change the texture if it's not already set (in the example above it will run loadTexture over and over, unless you reset the car.x coordinate)
2) If you can't preload the image up front, then you can load it during play. Look at the "Loader Events" example code for details.
3) You need to check the sprite position in update and not create (as it won't have moved at all by that point).

Multitouch Pinch, Pan, Zoom in HTML 5 Canvas

I have most of a module written to handle multitouch pinch, pan and zoom on an HTML 5 canvas element. I will share it below. I've been developing in JavaScript for some time now, and this one continues to boggle me. If anybody has any insights, I will post the final version up on stack for everybody to share once it is confirmed working on my iPad.
Here is what I am doing:
touchmove events trigger the changing of variables. I use these variables to change the way in which my image is painted onto the canvas. I have eight variables, each corresponding to the options that can be put into the drawImage() function. These eight variables get updated through functions that increment/decrement their values and keep them within a certain range. The variables are closure variables, so they are global throughout my module. To prevent over-processing, I make a call to this drawImage() function once every 40ms while the user has their finger pressed to the screen using a setInterval().
Here is the problem:
touchmove events seem to be causing a race condition where my variables get updated by many different instances of that same event. I can somewhat confirm this through my console output, that tracks one variable that is bounded to never reach below 20. When I swipe in one direction quickly, that variable dips down far below 20. Then when I release my finger, swipe slowly, it returns to 20. Another thing that points me in this direction, when I look at these variables while stepping through my program, they differ from what my console.log() pumps out.
Note: The code successfully draws the image the first time, but not anytime thereafter. A basic rendition of my code is below... The full version is on GitHub inside the Scripts folder. It is a Sencha Touch v1.1 app at heart
function PinchPanZoomFile(config)
{
/*
* Closure variable declaration here...
* Canvas Declaration here...
*/
function handleTouchStart(e) {
whatDown.oneDown = (e.originalEvent.targetTouches.length == 1) ? true : false;
whatDown.twoDown = (e.originalEvent.targetTouches.length >= 2) ? true : false;
drawInterval = setInterval(draw, 100);
}
function handleTouchEnd(e) {
whatDown.oneDown = (e.originalEvent.targetTouches.length == 1) ? true : false;
whatDown.twoDown = (e.originalEvent.targetTouches.length >= 2) ? true : false;
clearInterval(drawInterval);
}
function handleTouchMove(e) {
if(whatDown.twoDown) {
/*
* Do Panning & Zooming
*/
changeWindowXBy(deltaDistance); //deltaDistance
changeWindowYBy(deltaDistance); //deltaDistance
changeCanvasXBy(deltaX); //Pan
changeCanvasYBy(deltaY); //Pan
changeWindowDimsBy(deltaDistance*-1,deltaDistance*-1); //(deltaDistance)*-1 -- get smaller when zooming in.
changeCanvasWindowDimsBy(deltaDistance,deltaDistance); //deltaDistance -- get bigger when zooming in
} else if(whatDown.oneDown) {
/*
* Do Panning
*/
changeWindowXBy(0);
changeWindowYBy(0);
changeCanvasXBy(deltaX);
changeCanvasYBy(deltaY);
changeWindowDimsBy(0,0);
changeCanvasWindowDimsBy(0,0);
}
}
function draw() {
//Draw Image Off Screen
var offScreenCtx = offScreenCanvas[0].getContext('2d');
offScreenCtx.save();
offScreenCtx.clearRect(0, 0, canvasWidth, canvasHeight);
offScreenCtx.restore();
offScreenCtx.drawImage(base64Image,
parseInt(windowX),
parseInt(windowY),
parseInt(windowWidth),
parseInt(windowHeight),
parseInt(canvasX),
parseInt(canvasY),
parseInt(canvasWindowWidth),
parseInt(canvasWindowHeight)
);
//Draw Image On Screen
var offScreenImageData = offScreenCtx.getImageData(0, 0, canvasWidth, canvasHeight);
var onScreenCtx = canvas[0].getContext('2d');
onScreenCtx.putImageData(offScreenImageData, 0, 0);
}
}
I strongly recommend using Sencha Touch 2.0.1, as it supports a lot of the touch events you need. See http://dev.sencha.com/deploy/touch/examples/production/kitchensink/#demo/touchevents for examples.

Categories