So I have spritesheet i have almost looked everywhere nor i can find good tutorial neither i can get this thing to work .Can some one point it out for me that what's wrong here.?Coz none error is generated nor is anythign getting showed on the canvas .
var result = queue.getResult("avatar1");
var data=
{
images: [ result],
// The 5th value is the image index per the list defined in "images" (defaults to 0).
frames: [
// x, y, width, height, imageIndex, regX, regY
//head_south":{"x":120,"h":20,"y":138,"w":15}
[120,138,15,20],
[64,0,15,20,2],
],
animations: {
show: { frames: [0,1], next: true, frequency: 1 }
}
};
var sp = new createjs.SpriteSheet(data);
createjs.Ticker.setFPS(60);
var sprite_anim = new createjs.BitmapAnimation(sp,"show");
sprite_anim.x=100;
sprite_anim.y=100;
stage.addChild(this.sprite_anim);
sprite_anim.play("show");
sprite_anim.gotoAndPlay('show');
Do you update the stage with the ticker ? :
createjs.Ticker.addEventListener("tick", function(event) {
stage.update(event);
});
4 arguments [120,138,15,20], 5 arguments [64,0,15,20,2]
Arguments that are allowed are either 4 or 7.So changed back to 4.That was why it was generating error of" createjs type error '.
Thank everyone for your conern .Closing this question.
Related
The goal of my project is to make a tree planting game. When the game starts it should already have say, 10 trees in random positions as a starting point. Then, the duck can plant trees via moving with the cursor and planting with the spacebar. Every 1 second that passes, i want a random number of trees between 5-15 inclusive to destruct on their own. There will be a counter for the number of trees currently on screen and it updates every second. Game over when it hits 0.
Here is what I have so far/planning on implementing:
Counter for the trees
Duck moving and planting on canvas
Here is what I'm having trouble with:
Getting the game to already start off with 10 trees.
I am getting an error message that says that onEvent() method is not defined when it seems like it is in the code for destroying trees.
Here is my code so far, trying to implement the destruction of trees and I do not know how to instantiate the initial 10 trees :( :
As you can see, I've already tried fix the onEvent not defined error by putting it before i call the method but im still recieving the same error.
class Scene2 extends Phaser.Scene{
constructor(){
super("playGame");
}
//var timedEvent;
onEvent(){
for(var i = 0; i<2; i++){
var tree = this.projectiles.getChildren()[i];
tree.update();
}
}
create(){
this.grass = this.add.tileSprite(0,0,config.width,config.height,'grass').setOrigin(0,0);
//maybe add loops (and some updated sprites) for animals to move in place. i can learn that from one of gamedev acad's tutorials.
this.ella = this.add.sprite(200, 400, "ella"); // later do random spots
this.ella.play("ella_anim");
this.ella.setScale(.45);
this.tiger = this.add.sprite(500, 200, "tiger"); // later do random spots
this.tiger.play("tiger_anim");
this.tiger.setScale(.4);
this.monkey = this.add.sprite(100, 100, "monkey"); // later do random spots
this.monkey.play("monkey_anim");
this.monkey.setScale(.4);
this.duck =this.physics.add.sprite(200,300, "duck");
var follower = this.duck.setDepth(100);
follower.play("duck_anim");
follower.setScale(.6);
this.input.on('pointermove', function(pointer)
{
this.physics.moveToObject(follower, pointer, 240);
},this);
follower.setCollideWorldBounds(true);
//follower.setScale(.5);
this.add.text(20,20, "Playing game", {font: "25px Arial", fill: "yellow"});
this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
var timedEvent = this.time.addEvent({ delay: 1000, callback: onEvent, callbackScope: this, loop: true });
this.projectiles = this.add.group(); //holds all the trees
}
update(){
text.setText('Event.progress: ' + timedEvent.getProgress().toString().substr(0, 4));
if(Phaser.Input.Keyboard.JustDown(this.spacebar)){
this.plantTree();
}
}
plantTree(){
var tree = new Tree(this).setScale(.2);
}
}
This is the tree class:
class Tree extends Phaser.GameObjects.Sprite{
constructor(scene,place){
var x = scene.duck.x;
var y = scene.duck.y;
super(scene,x,y, "tree");
scene.add.existing(this);
}
update(){
this.destroy();
}
}
I'm fairly new to Phaser. Pls let me know if you know the answer to how to instantiate trees in the game initially and how to fix the error with onEvent. Thanks.
Error is:
Uncaught ReferenceError: onEvent is not defined
at Scene2.create (Scene2.js:44)
at initialize.create (phaser.min.js:1)
at initialize.bootScene (phaser.min.js:1)
at initialize.start (phaser.min.js:1)
at initialize.processQueue (phaser.min.js:1)
at initialize.update (phaser.min.js:1)
at initialize.step (phaser.min.js:1)
at initialize.step (phaser.min.js:1)
at e (phaser.min.js:1)
I'm working on a project and I need to add 3d sounds effects, like the sound is continually moving around the listener effects. Is it possible to achieve that with howlerjs i see that with howler i'm able to play a sound from specific coordinates/orientation but how to achieve surrounding/ambisonics sounds ?
Or another library in JavaScript to achieve that?
Thanks for your help.
Half a year late, but yeah that's entirely possible in howler.js, haven't used it myself but judging from the docs you can just update the position. there's some more libraries that do it that I've found, check here how 3dage does exactly what you want:
https://codepen.io/naugtur/pen/QgmvOB?editors=1010
var world = IIIdage.World({
tickInterval: 200
})
var annoyingFly = IIIdage.Thing({
is: ['fly'],
sounds: {
'buzzing constantly': {
sound: 'buzz',
times: Infinity
}
},
reacts: [
{
// to: world.random.veryOften(),
to: world.time.once(),
with: 'buzzing constantly'
}
]
})
// scene should create and expose a default world or accept one
var scene = IIIdage.Scene({
title: 'Annoying fly',
library: {
sounds: {
'buzz': {
src: ['https://webaudiogaming.github.io/3dage/fly.mp3']
}
}
},
world: world,
things: [ // scene iterates all things and spawns them into the world. same can be done manually later on.
annoyingFly({
pos: [-1, -15, 0],
dir: [1, 0, 0],
v: 1
})
]
}).load().run()
setTimeout(function () {
scene.dev.trace(IIIdage.dev.preview.dom())
}, 500)
setInterval(function rotateVector() {
var angleRad = 0.15
var d=scene.things[0].attributes.dir
var x=d[0], y=d[1]
var cosAngle = Math.cos(angleRad), sinAngle = Math.sin(angleRad)
scene.things[0].attributes.dir = [x * cosAngle - y * sinAngle, y * cosAngle + x * sinAngle, 0]
}, 500)
window.scene = scene
There's still some others that do similar stuff:
https://www.npmjs.com/package/songbird-audio
https://www.npmjs.com/package/ambisonics
Hope this pushes you in the right direction if you still want help with it.
I'd been trying to write a small library in Javascript mainly for Canvas drawImage() method.
The main purpose of the library is to pass array values instead of passing single values such as :
// srcPos=[0,0] , size=[90,90], dstPos=[50,50]
function draw_image(context, image, srcPos, size, dstPos, size) {
context.drawImage(image, srcPos[0], srcPos[1], size[0], size[1], dstPos[0], dstPos[1], size[0], size[1]);
}
but when i called this function jzz like this, I'm getting Uncaught ReferenceError :
var canvas = document.getElementById("display"),
frame = canvas.getContext("2d");
var shipInfo = { center:[45, 45], size:[90, 90], radius: 35, angle:45 },
shipImage = new Image(),
pos = [40, 70];
shipImage.src = "ship.png";
function draw() {
draw_image(frame, shipImage, shipInfo.size, pos, shipInfo.size);
}
window.onload = function() {
draw();
}
And Is it possible to implement a method overriding the default drawImage() like this:
frame.draw_image(shipImage, srcPos, shipInfo.size, dstPos, shipInfo.size);
If you want to add a function to the 2d context, javascript makes this easy thanks to the prototype inheritance : You can inject the Context2D object to add or change its function as you wish.
You might want to look at a few addings i made to the context in a small canvas lib i made here : https://github.com/gamealchemist/CanvasLib
Some will tell that injecting is evil, but unless you're on a huge boat i would just say : If you use some graphic library, respect the semantic of existing functions and everything should be fine. If you don't use libs : do whatever it takes !
So, to answer more specifically to your question, your shorter drawImage would give :
CanvasRenderingContext2D.prototype.draw_image = function ( image,
srcPos, size,
dstPos, size) {
this.drawImage(image, srcPos[0], srcPos[1], size[0], size[1],
dstPos[0], dstPos[1], size[0], size[1]);
};
Then you can use the new function on all your contexts :
var canvas = document.getElementById("display"),
frame = canvas.getContext("2d");
frame.draw_image( ... ) ;
Notice that you could use 'rect' objects, which would be arrays with 4 elements, x, y, w, h, and lead to an even shorter syntax.
Edit : i see in your lib that you want to rotate your rect.
First thing is that you don't want to reset the transform. Just save it then restore it.
I would try something closer to this :
var x = dstPos[0],
y = dstPos[1],
halfWidth = dstSize[0]*0.5, // !! not src use >>1 if you know it's an int.
halfHeight = dstSize[1]*0.5, // !! not src ...
angleInRads = angle * Math.PI / 180;
this.save();
this.translate(x+halfWidth,y+halfHeight);
this.rotate(angleInRads);
this.drawImage(image
, center[0], center[1], srcSize[0], srcSize[1]
, -halfWidth, -halfHeight, dstSize[0],dstSize[1]);
this.restore();
Your small image library would fit well inside a javascript object.
A Demo: http://jsfiddle.net/m1erickson/7pZJw/
A javascript object can hold information about your image:
the image itself
the image size (can be automatically calculated for you)
the image centerpoint (can be automatically calculated for you)
Example:
// create a new object
// fill it with the info about the image
var object={
image:shipImage,
width:shipImage.width,
height:shipImage.height,
centerOffsetX:shipImage.width/2,
centerOffsetY:shipImage.height/2,
radius:35,
angle:45,
};
A javascript object can also hold functions that draws the image (as you've done in your code)
Example:
// when you call object.draw the image will be drawn by this function
// which is added to the object itself
draw:function(context,atX,atY,newWidth,newHeight){
context.drawImage(
this.image,
0,0,this.width,this.height,
atX,atY,newWidth,newHeight);
},
A function to create your small image library inside a javascript object might look like this:
function createImageObject(image,radius,angle){
// create a new object
// fill it with the info about the image
var object={
image:image,
width:image.width,
height:image.height,
centerOffsetX:image.width/2,
centerOffsetY:image.height/2,
radius:radius,
angle:angle,
draw:function(context,atX,atY,newWidth,newHeight){
context.drawImage(
this.image,
0,0,this.width,this.height,
atX,atY,newWidth,newHeight);
},
};
return(object);
}
And you can use your ship object library like this:
// create a new ship object
var shipObject=createImageObject(img,35,45);
// draw the ship image using the ship object
// draw at 20,20 with size 75,75
shipObject.draw(frame,20,20,75,75);
BTW, I see you're using the version of drawImage that will scale/clip the source image.
If you just want to draw the full image at its original size you can do this shortcut:
// draw the image full-sized at x,y
context.drawImage(image,x,y);
I am Currently Trying to work with JavaScript in a cleaner object orientated way, So Please excuse me if I'm doing this entirely incorrectly I am using this previous questions answer as a general reference, but Here's my 'test' code:
//Create some sample objects to play with.
var testJSON = {
"rectangle": [
{ "id":3 , "x":5, "y":10, "width":10, "height":50
}
]
};
//Create Rectangle Constructor
var rectangle = {
init: function( i, x, y, width, height ) {
this.id = i,
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.fields = []
},
move: function( x, y ) {
this.x += x;
this.y += y;
}
};
//Create test array to hold all the objects
var test = [];
//Create a new rectangle object
var myRectangle = Object.create( rectangle );
myRectangle.init( 1, 0, 0, 2, 4 );
myRectangle.move( 3, 5 );
//put rectangle object in array associated with id
test[myRectangle.id] = myRectangle;
//Create a new rectangle object with the same variable name as it will all be in an array anyway.
var myRectangle = Object.create( rectangle );
myRectangle.init( 2, 0, 0, 2, 4 );
myRectangle.move( 0, 0 );
//put rectangle object in array associated with id
test[myRectangle.id] = myRectangle;
//put JSON result in
test[testJSON.rectangle[0].id] = testJSON.rectangle[0];
//No Longer need this variable, is it worth getting rid of.. i dont know
myRectangle =null;
//Try and use methods created in the constructor.
test[2].move(4,8);
console.log(test);
Okay, Now the actual questions, The Application I am trying to create, has both json data and it will have users that create data, so for example: the application will generate a bunch of 'rectangles' and then the user can also create rectangles.
So the first question would be, 'Is this the correct approach' and then secondly how would i get the json data to also have the method defined in the rectangle constructor (move)?
Any Help Greatly Appreciated.
This an extension of what #Marc B and #Ray Toal mentioned...
You have created javascript functions - which is not at all that bad - but not JSON. To create graphics, you could use the canvas tag as, in effect, a "drawing div" and use the object's x and y positions to constantly update them - if you were considering doing 2d animation. If so, I would recommend CreateJs as a starting block before hard-coding JAVASCRIPT animations. Again, you're code is just fine, but having users create this data - if you were considering a server application would involve using real JSON or perhaps Node.js - but for now I'd focus on single player aspect and setting up you're objects on a graphical 'interface' like <canvas>
You find much infos to trailing commas here:
Are trailing commas in arrays and objects part of the spec?
It's about the comma at "right there".
[
{ title: "..", display: function() { return ".."; } },
{ title: "..", display: function() { return ".."; } },
{ title: "..", display: function() { return ".."; } }, // <--right there
]
My problem is now, that a 3rd party tool generates this list with a trailing comma and I am not able to access the sourcecode of this tool. I
<body>
my stuff
<!-- the folloging div with the javascript comes from the 3rd party -->
<div class="item"><script type="text/javascript">
$(document).ready(function() {
$.supersized({
// Functionality
slide_interval : 8000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 400, // Speed of transition
fit_always : 0, //Prevents the image from being cropped by locking it at 100% width.
min_width : 600, //min-width of images
random : 0, //random img
vertical_center : 1, //vertical alignment
// Components
slide_links : 'false', // Individual links for each slide (Options: false, 'number', 'name', 'blank')
slides : [ // Slideshow Images
{image : 'image1.jpg', otherstuff: 'blah', moreotherstuff: 'lorem'},
{image : 'image2.jpg', otherstuff: 'blub', moreotherstuff: 'ipsum'},
]
});
});
</script></div>
And now I am asking me is there any way to get this working in IE7/IE8.
The only way I see right now (as i can't edit the 3rd party and can't access it on the server) is:
- give a special output without that div
- request the normal side via ajax
- parse everything, get this div, delete last comma and execute the javascript
that's realy not the way I want do it. Is there another way I could solve this?
IE7/IE8 will report 1 element bigger array length, unless you trim those arrays.
If you know all JS methods which accepts data from 3rd party you can write wrapper for them. For example:
var removeEmpty = function(array){
var i, result = [];
for (i = 0; i < array.length; ++i){
if ( typeof array[i] != 'undefined' ){
result.push(array[i]);
}
}
return result;
};
$.supersized = (function() {
var origMethod = $.supersized;
return function(config) {
config.slides = removeEmpty(config.slides); // get rid of undefined data in array
return origMethod.call(this, config); // call original method
};
}());
No, there is no way to get those trailing commas working in IE. It simply can't be done; it's a fundamental part of the browser's javascript parser.
This is an extremely well-known issue, which means that your third party tool is very obviously faulty and clearly hasn't been tested properly. I don't know where you got it from, but if you paid for it, I'd be complaining loudly if I were you.
If you really can't deal with the problem at source, then your only option remaining is to fix the generated code before it gets into IE. That much is easier said than done. Depending on the complexity of the generated code, you might be able to write a regex for it if it's simple and predictable, but if the code it generates is complex or of varying complexity, I suspect you may be in trouble with that idea.