kittykatattack / learningpixi Goto Github PK
View Code? Open in Web Editor NEWA step-by-step introduction to making games and interactive media with the Pixi.js rendering engine.
A step-by-step introduction to making games and interactive media with the Pixi.js rendering engine.
Then link to 'ParticleContainer documentation' in the Using a ParticleContainer to group sprites section, pointing to http://pixijs.github.io/docs/PIXI.ParticleContainer.html returns a 404 error.
Not sure if this is the right place to ask buttt yeah.
It would also work if I could give a specific sprite a different scale mode.
I only know how to set the option globally.
Hello,
The code in https://github.com/kittykatattack/learningPixi/blob/master/examples/12_keyboardMovement.html is not quite correct in my opinion. Steps to reproduce:
The behavior of the step 3) is not correct. The sprite should run to the right because the right arrow is still pressed.
function setup() {
//Create the
tileset
sprite from the texture
var texture = TextureCache["images/tileset.png"];//Create a rectangle object that defines the position and
//size of the sub-image you want to extract from the texture
var rectangle = new Rectangle(192, 128, 64, 64);//Tell the texture to use that rectangular section
texture.frame = rectangle;//Create the sprite from the texture
var rocket = new Sprite(texture);//Position the rocket sprite on the canvas
rocket.x = 32;
rocket.y = 32;//Add the rocket to the stage
stage.addChild(rocket);//Render the stage
renderer.render(stage);
}
Here you have the line var rectangle = new Rectangle(192, 128, 64, 64);
which indicates to begin a rectangle at x value 192, y value 128, and create a rectangle of size 64x64. Any rectangle beginning at 192 pixels will be invalid given that the entire tileset image size is 192 pixels, and also the individual images on the tileset are 32x32 not 64x64.
This line should be replaced as such:
var rectangle = new Rectangle(96, 64, 32, 32);
Hi, I'm new to Pixi and I've been following the tutorial until "Creating Sprite". I followed the codes but my browser wasn't showing any images.
I don't know why it's not working.
<html>
<style>* {padding: 0; margin: 0}</style>
<head>
<meta charset="utf-8">
<title>Test PIXI</title>
</head>
<script src="pixi/pixi.min.js"></script>
<body>
<script type="text/javascript">
//Create a Pixi Application
let app = new PIXI.Application();
//Add the canvas that Pixi automatically created for you to the HTML document
document.body.appendChild(app.view);
PIXI.loader.add("images/alien_a.png").load(setup);
function setup()
{
let cat = new PIXI.Sprite(PIXI.loader.resources["images/alien_a.png"].texture);
app.stage.addChild(cat);
}
</script>
</body>
</html>
I've an image file located in folder "images" and I have a "pixi" folder storing pixi.min.js file
From the Browser's console there's an error message
Uncaught DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The image element contains cross-origin data, and may not be loaded.
I cannot even find TextureCache in the documentation, only found it being mentioned in some old thread as a part of PIXI.utils
Hi ! Thanks a lot for your PixiJs examples.
I think there is a little error in the example just after the keyboard() function code here :
keyObject.release = () =>) {
The right line code should be :
keyObject.release = () => {
I am trying to follow the tutorial, but i cant get anything to render. I am on this step and i have copied the code EXACTLY as it is shown (except for the path to the image, which is 'images/cat.png' in my case). I am 100% sure that the image is downloaded and in the correct directory. In the web developer console, I get the error "Error: WebGL warning: drawElements: This operation requires zeroing texture data. This is slow. SpriteRenderer.js:442:13" and the only thing that is displayed is a black 256x256 sqaure (the canvas). This is really frusturating me. Does anyone know what the problem could be?
I keep getting the error 'Resource with name "' + name + '" already exists.'
I don't really care what is going on under the hood, I guess I have to check each time I add an image to see if it is already there - how do i do that?
This seems like something an intro tutorial might want to cover....
I am facing this isssue from last 2 months, when i try to add gradiant and inner or outer shadow in words or numerics on win numbers like photoshop, can someone help me to get more information for this issue or is that any option available on Pixi.
There have been a few small user-facing API changes in the most recent release of Pixi.
Is anyone help update the README doc and the example files?
[Help Wanted] I have read the part of the book about the global position and local position. However I am stuck on using the containsPoint
function of the PIXI.Sprite
class. I can never get it to work correctly. Suppose I put everything into a parent container which is in stage. My player sprite is moving around using your camera centerOver
function in GameUtilities
. When I move it the player rotates towards the mouse position. I want to check if other sprite is intersecting with my sprite's rectangle clip. So I check if the anchor of other sprites are contained in my sprite's clip, which is also a rectangle sprite. The clip sprite is just next to my player sprite and facing to the mouse direction. If an examining sprite is contained in the clip I will change the color of the sprite. Sadly none of the sprites is contained in the clip sprite as I move my player sprite around the map.
I have also tried getBounds().contains(x, y)
, and getLocalBounds().contains(x, y)
. None of them works.
And I have tried your hitTestCircleRectangle()
method in bump.js
. This one does work, finally. However it is not very accurate. The color of the examining sprite changes but some of them are outside of the bound of my clip sprite, which is not far away but the distance is noticeable.
Any hint on this one?
In my html:
<div class="pixiTestBox">
<!-- here i will append one app view (canvas) -->
</div>
<div class="pixiTestBox2">
<!-- here i will append another app view (canvas) -->
</div>
In my js:
//NOTE: When document is loaded, calls automatically `pixiSetup()` and `pixiSetup2()`
pixiSetup()
{
//creates and append the "app.view" to div.pixiTestBox
var ctx = document.querySelector(".pixiTestBox");
var app = new PIXI.Application(800, 600,
{
backgroundColor: 0x1099bb
});
ctx.appendChild(app.view);
// create a new Sprite from an image path
var bunny = PIXI.Sprite.fromImage('images/user.png');
// center the sprite's anchor point
bunny.anchor.set(0.5);
app.stage.addChild(bunny);
// Pointers normalize touch and mouse
app.renderer.plugins.interaction.on('pointerup', canvasOnClickHandler);
//Set element react on click
bunny.interactive = true;
bunny.on('pointerdown', drawedElementClicked);
}
pixiSetup2()
{
//creates and append the "app.view" to div.pixiTestBox2
var ctx = document.querySelector(".pixiTestBox2");
var app = new PIXI.Application(800, 600,
{
backgroundColor: 0x1099bb
});
ctx.appendChild(app.view);
// create a new Sprite from an image path
var bunny = PIXI.Sprite.fromImage('images/user.png');
// center the sprite's anchor point
bunny.anchor.set(0.5);
app.stage.addChild(bunny);
// Pointers normalize touch and mouse
app.renderer.plugins.interaction.on('pointerup', canvasOnClickHandler);
//Set element react on click
bunny.interactive = true;
bunny.on('pointerdown', drawedElementClicked);
}
function canvasOnClickHandler(event)
{
//How can i get here if the canvas that was clicked was the one inside of div class="pixiTestBox" or div class="pixiTestBox2"?
} //canvasOnClickHandler
function drawedElementClicked(event)
{
//How can i get here wich sprite was clicked? (is it possible to add an "id" when declaring a sprite and get his id here?)
} //drawedElementClicked
How can i accomplish what is in canvasOnClickHandler() and drawedElementClicked()?
Put at the beginning of Readme what version of Pixi.js is used. There's some changes here and there in Pixi.js and putting that will make the Guide consistent.
404
In the 7th File when i run the code an issue regarding Texture dimension appears.
Texture Error: frame does not fit inside the base Texture dimensions: X: 192 + 64 > 192 Y: 128 + 64 > 192.
How do you resolve this issue?
Hello there! Thank you very much for the fantastic tutorial! :)
I think there is potentially an issue with the following line(s) of code in the Moving Sprites section of the tutorial concerning the use of delta time:
cat.x += 1 + delta;
If I'm not mistaken, delta
is not "the amount of fractional lag between frame", it is the fractional variation from the ideal time (1000 ms / 60) since the the last frame, that is:
app.ticker.add((delta) => {
console.log(1000 / 60 * delta === app.ticker.elapsedMS) // returns true most of the time (not all the time presumably because of floating point rounding errors)
});
As such, on a machine that is rendering at approximately 60 FPS, the cat would be moving at approximately 2 pixels per frame, instead of the 1 pixel per frame suggested in the tutorial with the current code.
Since delta is effectively the number of ideal frames (at a rate of 60 FPS) passed since the last frame, and we want to achieve 1 pixel per ideal frame, I think the correct code should be:
app.ticker.add((delta) => {
cat.x += delta;
});
As an aside, the gameLoop()
function is currently declared outside of the scope of the setup()
function and does not have access to the cat variable:
function setup() {
//Start the game loop by adding the `gameLoop` function to
//Pixi's `ticker` and providing it with a `delta` argument.
app.ticker.add(delta => gameLoop(delta));
}
function gameLoop(delta){
//Move the cat 1 pixel
cat.x += 1;
}
If it's not intentional and if I'm not mistaken, the gameLoop()
function should either be declared inside the setup()
function or that the cat
variable should be passed in.
I'm relatively new to this so many apologies in advance if it's a false alarm! I'm more than happy to create a PR and edit the related parts, too!
I hope that helps! Happy coding! :)
About the stage and renderer, it seems we no longer need to setup the stage ourselves since it's already a property of the pixi application? We also dont need to call renderer.render(graphic), because pixi does that automatically?
I've only figured those out from the examples here : http://pixijs.github.io/examples/#/basics/spritesheet.js
I never used pixi so maybe you'd know more than me about what parts to modify, but it looks like this tuto needs a lot of refactoring.
I'm a college student majoring in CS from China. I consider that your book is so great, so I want to ask if I could translate it from English to Chinese in my free time. It will be also free in my github, and it will have a mark that it's translated from you.
When cropping the sub-image of rocket:
let rectangle = new Rectangle(192, 128, 64, 64);
should be
let rectangle = new Rectangle(96, 64, 32, 32);
I copy-pasted the following code into my program:
var message = new Text(
"Hello Pixi!",
{fontFamily: "Arial", fontSize: 32, fill: "white"}
);
message.position.set(54, 96);
stage.addChild(message);
and it shows the following error in my browser's console:
Uncaught TypeError: Cannot read property 'set' of undefined
Can someone tell me what's undefined in my code?
Also, i have the whole code:
<!doctype html>
<title>Hello World</title> <script src="pixi.min.js"></script> <script type="text/javascript"> var type = "WebGL" if(!PIXI.utils.isWebGLSupported()){ type = "canvas" }PIXI.utils.sayHello(type);
//Aliases
var Container = PIXI.Container,
autoDetectRenderer = PIXI.autoDetectRenderer,
loader = PIXI.loader,
resources = PIXI.loader.resources,
Sprite = PIXI.Sprite;
TextureCache = PIXI.utils.TextureCache;
//Create a Pixi stage and renderer and add the
//renderer.view to the DOM
var stage = new Container(),
renderer = autoDetectRenderer(256, 256);
document.body.appendChild(renderer.view);
loader
.add("images/myspritesheet.json")
.load(setup);
var sprite;
function setup() {
var texture = TextureCache["heart.png"];
sprite = new Sprite(texture);
sprite.y=30;
stage.addChild(sprite);
var message = new Text(
"Hello Pixi!",
{fontFamily: "Arial", fontSize: 32, fill: "white"}
);
message.position.set(54, 96);
stage.addChild(message);
gameLoop();
}
function gameLoop() {
requestAnimationFrame(gameLoop);
sprite.x += 1;
renderer.render(stage);
}
</script>
Hey thanks for create this, awesome job! :) very clear to understand and it was my best choice in a jungle of other links
I have 4 images loaded of a character running. Is the right way to do it to addChild and removeChild? That doesn't seem right!
The animation ought to be able to be stopped! (ideally set to the frame where two feet are planted on the ground).
Also thank you so much for this document! IT is so extremely useful!
PIXI.loader .add("pictures/Mech1Walk.png") .load(setup);
(why did author omit PIXI. prefix???)
`function setup() {
var texture = PIXI.TextureCache["images/tileset.png"];
var rectangle = new PIXI.Rectangle(1, 1, 64, 64);
texture.frame = rectangle;
var robot = new PIXI.Sprite(texture);
robot.x = 100;
robot.y = 100;
stage.addChild(robot);
renderer.render(stage);
}`
Gives me this error:
Uncaught DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at ... (path to my picture);
Any advice on how to do this for OS X? I installed Mongoose, but I'm not sure exactly how to launch it in my project folder.
Thanks,
J
In your guide, you give instructions on how to execute keyboard commands. Well, I've implemented your example code, and it works. But the problem lies in when I get a gameover and need to restart everything. If I try running a gameover function that resets everything and reruns the setup() function, I end up with all of my keyboard inputs getting duplicated somehow and executing multiple times per button press. I think this has to do with the event listeners being added to the window, but is there any way I can get around this?
Thanks.
function keyboard(keyCode) {
var key = {};
key.code = keyCode;
key.isDown = false;
key.isUp = true;
key.press = undefined;
key.release = undefined;
//The `downHandler`
key.downHandler = function(event) {
if (event.keyCode === key.code) {
if (key.isUp && key.press) key.press();
key.isDown = true;
key.isUp = false;
}
event.preventDefault();
};
//The `upHandler`
key.upHandler = function(event) {
if (event.keyCode === key.code) {
if (key.isDown && key.release) key.release();
key.isDown = false;
key.isUp = true;
}
event.preventDefault();
};
//Attach event listeners
window.addEventListener(
"keydown", key.downHandler.bind(key), false
);
window.addEventListener(
"keyup", key.upHandler.bind(key), false
);
return key;
}
Could you mention keyboard control for multiple keyboards?
Pressing different keys while other is pressed can make some issues
10.Make a sprite from a tileset sub-image
There's a mistake.
In this code:var rectangle = new Rectangle(192, 128, 64, 64);
Trigger error:
Texture Error: frame does not fit inside the base Texture dimensions
I checked.
let app = new PIXI.Application({ width: 256, height: 256, antialias: true, transparent: false, resolution: 1 } );
If you're happy with Pixi's default settings, you don't need to set any of these options, except of course the
width
andheight
(But, if you need to, see Pixi's documentation on PIXI.ApplicationWhat do those options do?
antialias
smoothes the edges of fonts and graphic primitives. (WebGL anti-aliasing isn’t available on all platforms, so you’ll need to test this on your game’s target platform.)transparent
makes the canvas background transparent.resolution
makes it easier to work with displays of varying resolutions and pixel densities. Setting the resolutions is a little outside the scope of this tutorial, but check out Mat Grove's explanation about how to useresolution
for all the details. But usually, just keepresolution
at 1 for most projects and you'll be fine.
Based on the PIXI.Application
documentation, I think it makes sense to mention that transparent
and resolution
are set to false
and 1
, respectively, by default. Moreover, it is not required to set width
and height
because they default to 800
and 600
, respectively.
I am sorry for nitpicking. I just think that the phrasing can be improved. Thanks a lot for this masterpiece 👏 🙌
When in test the code of this tutorial :
<!DOCTYPE HTML>
<html>
<head>
<title>Test de Pixi</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/4.7.1/pixi.min.js"></script>
<script type="text/javascript">
let type = "WebGL"
if(!PIXI.utils.isWebGLSupported()){
type = "canvas"
}
PIXI.utils.sayHello(type)
let app = new PIXI.Application({width: 256, height: 256});
document.body.appendChild(app.view);
</script>
</head>
<body>
</body>
</html>
I don't have a black square. And this a the console :
PixiJS 4.7.1 - canvas - http://www.pixijs.com/
index.js:258
Error: WebGL warning: Disallowing antialiased backbuffers due to blacklisting.
index.js:297:16
Error: WebGL warning: Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
index.js:297:16
Error: WebGL warning: Failed to create WebGL context: WebGL creation failed:
* Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
* Exhausted GL driver options.
index.js:297:16
Error: WebGL warning: Disallowing antialiased backbuffers due to blacklisting.
index.js:297:4
Error: WebGL warning: Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
index.js:297:4
Error: WebGL warning: Failed to create WebGL context: WebGL creation failed:
* Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
* Exhausted GL driver options.
index.js:297:4
Error: WebGL warning: Disallowing antialiased backbuffers due to blacklisting.
index.js:297:16
Error: WebGL warning: Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
index.js:297:16
Error: WebGL warning: Failed to create WebGL context: WebGL creation failed:
* Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
* Exhausted GL driver options.
index.js:297:16
Error: WebGL warning: Disallowing antialiased backbuffers due to blacklisting.
index.js:297:4
Error: WebGL warning: Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
index.js:297:4
Error: WebGL warning: Failed to create WebGL context: WebGL creation failed:
* Refused to create native OpenGL context because of blacklist entry: FEATURE_FAILURE_OPENGL_1
* Exhausted GL driver options.
index.js:297:4
TypeError: document.body is null[En savoir plus]
index.html:14:9
L’encodage de caractères du document HTML n’a pas été déclaré. Le document sera affiché avec des caractères incorrects pour certaines configurations de navigateur si le document contient des caractères en dehors de la plage US-ASCII. L’encodage de caractères de la page doit être déclaré dans le document ou dans le protocole de transfert.
index.html
Why ?
Great article about pixi js. Could you let me know how can I integrate mobile app from PIXI.js. Whether I need phonegap, ionic or native-react. Please let me know this.
Cheers.
Sorry to make an issue for this: but I couldn't find any public contact info for the author of the guide.
I really would like to purchase the book as I am more than happy to pay for good instructional material, but the 2015 publication date put me off a bit.
Is it still recommended to purchase, or is there an updated version I should get instead?
I have read your excellent book Foundation Game Design with HTML5 and JavaScript many times :). While reading the book I searched for your web site but could not find it :( now I found your github account and site. It will be nice if you code a simple game engine like GA around pixi. However thanks for the excellent book and helpful code with explanation on github.
I thought every texture that Pixi create, will be stored in PIXI.utils.TextCache. But as use PIXI.loader
, Pixi’s development team recommends use PIXI.loader.resources
.
I am confused aboute it. So, I make a demo:
PIXI.loader
.add([
"images/1.png",
"images/2.png"
])
.load(function() {
var sprite = new PIXI.Sprite(PIXI.utils.TextureCache["images/[email protected]"]);
app.stage.addChild(sprite);
});
I found that PIXI.utils.TextCache
works well。
Can I always use PIXI.utils.TextCache
instead of PIXI.loader.resource
.
I've been using this for awhile:
http://renderhjs.net/shoebox/
Its free. Literally, this is the most easiest, hassle-free tool I found for awhile. It has a support for Pixi.js too! All you need to do is to drag all the files then boom! Its done, no complications. Good for tutorials too, especially if you don't want to waste your time learning how to configure a spritesheet (in a tutorial teaching game programming) complicated stuff are hidden through settings but there is nothing much to change.
Worth mentioning though.
Hello,I am Zain,from china.
I translate the learningPixi to chinese 1/10 in there:
learningPixi中文版
I will finish it in next mouth;
I hope to add this version to your tutorial.
Wish more people enjoy Pixi.js!!!~
First of all, myself and the internet thank you for creating such a valuable resource on pixi.
I have been using your keyboard function object for my last couple of projects but I can not seem to get it to work inside an iframe (I am trying to embed my game on my wordpress portfolio page). Is there any workaround you know of to make this code work in an iframe?
Kind Regards
it like this
sprite.set({
x: 100,
y:100,
anchor:0.5
});
set sprite attr one by one is too fussy , i want easy wat to set sprite attr,but i cant found any api in Internet .
i want to create a object( have all this frame sprite ) to control sprite's postion
Simply adding the pixi script file's source to a script tag in an html file as suggested in your tutorial and opening the file in whatever browser that the person uses is fine. There's no need to create a webserver for one to do pixi.js scripting.
The from
methods are bad!
http://www.html5gamedevs.com/topic/16019-preload-all-textures/
Re-wite the code so that sprites are created like this:
var sprite = new PIXI.Sprite(PIXI.loader.resources['image1.png'].texture);
Mat Grove's explanation link is broken, it displays: "Error establishing a database connection".
animations: {
selected: 'frame', // after frame complete changing selected to worm_move
frame: [0, 37],
worm_move: [38, 51]
}
frame = animations[animations.selected];
At runtime i'm fetching currentFrame in ticker. And checking if currentFrame === frameEnd then performing gotoAndStop(37). Now problem is when 1st sequence is stopped I want to play another sequence in loop eg. worm_move. Both sequence belong to same movieclip. First sequence is working fine But we are facing issue in second sequence
/** In ticker add both sequence are calling, when selected changed to second sequence(worm_move), it is not getting played **/
this.ticker.add(() => {
if (mc.currentFrame === frame[1]) {
mc.gotoAndStop(frame[1]);
}
});
Should be
var rectangle = new Rectangle(96, 64, 32, 32);
not
var rectangle = new Rectangle(192, 128, 64, 64);
Hello,
I'd like to know if the license of this tutorial is free. Is it allowed to translate it? (without forget to refer to the original of course)
function setup() {
//Create the `cat` sprite
var cat = new Sprite(resources["images/cat.png"].texture);
//Change the sprite's position
cat.x = 96;
cat.y = 96;
//Add the cat to the stage so you can see it
stage.addChild(cat);
//Render the stage
renderer.render(stage);
}
(Note: In this example, Sprite is an alias for PIXI.Sprite, TextureCache is an alias for PIXI.utils.TextureCache, and resources is an alias for PIXI.loader.resources as described earlier. I'll be using alias that follow this same format for all Pixi objects and methods in the example code from now on.)
Here you refer to an instance of TextureCache that isn't present in the example you use. It's also a bit unclear if we should be using TextureCache at all or not, as you DO use it during the tileset example.
I have absolutely no idea how I ran into this, but I just want to say THANK YOU for writing this. The Pixi.js documentation leaves much to be desired and I feel like I can finally start to use the library now that I've read this. So thanks, again!
The section where you talk about the state and how is linked to a play() function. Was of no use to me. I couldnt understand how is that useful for Scene switching. I see Phaser.io has a very good state system, and is very easy to switch from scene to scene. But in PIXI I have no idea how people are modularizing their games and working with models and separate files. Otherwise.. the game is all dumped into just 1 single file and is all spaguetti messy. Im going crazy looking for a good suggestion but I just cant fine sample code that bests illustrates a good simple Game Scene management in PIXI
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.