Pixi.js draw falling squares - javascript

I drawed a grid based system on canvas using PIXI.js.
I'm trying to animate the thing, first each particle position.y is -200, then using Tween.js I'm trying to make them fall.
I change the position to the correct position, which is particle._y.
As you notice you will see after falling there are some empty spaces and CPU is over heating.
http://jsbin.com/wojosopibe/1/edit?html,js,output
function animateParticles() {
for (var k = 0; k < STAGE.children.length; k++) {
var square = STAGE.children[k];
new Tween(square, 'position.y', square._y, Math.floor(Math.random() * 80), true);
}
}
I think I'm doing something wrong.
Can someone please explain me what I'm doing wrong and why there are some empty spaces after falling?

The reason for the empty spaces is that some of your animations are not starting. The cause is in this line:
new Tween(square, 'position.y', square._y, Math.floor(Math.random() * 80), true);
Looking at your function definition for Tween.js, I see this:
function Tween(object, property, value, frames, autostart)
The fourth parameter is frames. I'm assuming this is the number of frames required to complete the animation.
Well your Math.floor function willl sometimes return zero, meaning the animation will have no frames and won't start!!
You can fix this by using math.ceil() instead. This way there will always be at least 1 frame for the animation:
new Tween(square, 'position.y', square._y, Math.ceil(Math.random() * 80), true);
Now, as for performance, I would suggest setting this up differently...
Animating all those graphics objects is very intensive. My suggestion would be to draw a single red square, and then use a RenderTexture to generate a bitmap from the square. Then you can add Sprites to the stage, which perform WAY better when animating.
//Cretae a single graphics object
var g = new PIXI.Graphics();
g.beginFill(0xFF0000).drawRect(0, 0, 2, 2).endFill();
//Render the graphics into a Texture
var renderTexture = new PIXI.RenderTexture(RENDERER, RENDERER.width, RENDERER.height);
renderTexture.render(g);
for (var i = 0; i < CONFIG.rows; i++) {
for (var j = 0; j < CONFIG.cols; j++) {
var x = j * 4;
var y = i * 4;
//Add Sprites to the stage instead of Graphics
var PARTICLE = new PIXI.Sprite(renderTexture);
PARTICLE.x = x;
PARTICLE.y = -200;
PARTICLE._y = H - y;
STAGE.addChild(PARTICLE);
}
}
This link will have some more examples of a RenderTexture:
http://pixijs.github.io/examples/index.html?s=demos&f=render-texture-demo.js&title=RenderTexture

Related

How to Create a Multidimenisonal PRNG?

I am working on a procedural terrain generator, but the 3d Map is constantly morphing and changing, calling for at least 4d noise (5d if I need to make it loop). I haven't found a good perlin/simplex noise library that will work in this many dimensions, so I thought this would be a good time to learn how those algorithms work. After starting to make my own "perlin" noise, I found a large problem. I need to get a psudo random value based on the nD coordinates of that point. So far I have found solutions online that use the dot product of a single point and a vector generated by the inputs, but those became very predictable very fast (I'm not sure why). I then tried a recursive approach (below), and this worked ok, but I got some weird behavior towards the edges.
Recursive 3d randomness attempt:
function Rand(seed = 123456, deg = 1){
let s = seed % 2147483647;
s = s < 1 ? s + 2147483647 : s;
while(deg > 0){
s = s * 16807 % 2147483647;
deg--;
}
return (s - 1) / 2147483646;
}
function DimRand(seed, args){
if(args.length < 2){
return Rand(seed, args[0]);
}else{
let zero = args[0];
args.shift();
return DimRand(Rand(seed, zero), args);
}
}
var T = 1;
var c = document.getElementById('canvas').getContext('2d');
document.getElementById('canvas').height = innerHeight;
document.getElementById('canvas').width = innerWidth;
c.width = innerWidth;
c.height = innerHeight;
var size = 50;
function display(){
for(let i = 0; i < 20; i ++){
for(let j = 0; j < 20; j ++){
var bright = DimRand(89,[i,j])*255
c.fillStyle = `rgb(${bright},${bright},${bright})`
c.fillRect(i*size, j*size, size, size);
}
}
T++;
}
window.onmousedown=()=>{display();}
And here is the result:
The top row was always 1 (White), the 2d row and first column were all 0 (Black), and the 3d row was always very dark (less than ≈ 0.3)
This might just be a bug, or I might have to just deal with it, but I was wondering if there was a better approach.

Missing edges when stacking multiple geometries and using EdgesHelper

I am new to three.js so I am not sure whether I have made a mistake or my approach is wrong in the first place.
Check out my demo (use left and right arrow to navigate around):
http://www.ralphunden.de/files/kloetze/index.htm
The problem is that "inner edges" are not showing up:
http://i.imgur.com/vy8iH0J.png
The idea is to achieve a "blocky" look by using solid shapes with highlighted borders.
The best approach I have found is to use a BoxGeometry with a basic material and adding the outline with EdgesHelper.
The passed parameter shape is just a list of coordinates.
I am also not sure about adding the resulting meshes together like this (I do this so I can remove it from the scene comfortably later and it hasn't been a problem so far).
Here's the code:
function draw_shape(shape, offset, colour) {
var mesh = new THREE.Mesh();
for (var i = 0; i < shape.length; i++) {
var geometry = new THREE.BoxGeometry(BLOCKSIZE, BLOCKSIZE, BLOCKSIZE);
var material = new THREE.MeshBasicMaterial({ color: colour });
var tmp = new THREE.Mesh(geometry, material);
tmp.position.x = shape[i][0] * BLOCKSIZE - offset[0];
tmp.position.y = shape[i][1] * BLOCKSIZE - offset[1];
tmp.position.z = shape[i][2] * BLOCKSIZE - offset[2];
mesh.add(tmp)
var outline = new THREE.EdgesHelper(tmp, 0x000000);
outline.material.linewidth = 2;
mesh.add(outline);
}
return mesh;
}
Thanks in advance for any responses!
Ok. I faked it out like this:
var geometry = new THREE.BoxGeometry(BLOCKSIZE - 1 , BLOCKSIZE - 1, BLOCKSIZE - 1);
This means I made the boxes smaller by 1 which introduces a small gap to the nex box. This works and was something I tried early on but it looked very bad because the gap was too noticeable.
Then it struck me to try it again and at the same time increase BLOCKSIZE considerably so that the gap is be relatively smaller. At the same time I moved the camera further away by the same factor. (Ie. I increased BLOCKSIZE from 30 to 90 and moved the camera from about 200 to 600).
The result is satisfactory.

Very laggy animation in javascript

I have made a board with 156X64 divs 3 pixel each with border radius, so it looks like a board out of LED. I have string representing 0 or 1 of each 7X5 matrix of letters.
var lgeoa="00100001000001000001100011000101110";//7X5 matrix letter A
var lgeob="10000111000010001010100011000101110";//7X5 matrix letter B
and so on...
Drawing letter means change corresponding div background color. It is working fine, but after that I wanted to animate them the problem started. I clear line and draw in every 10 milliseconds, but its very very laggy. So please how can this code be optimized to work without lags?
P.S. Surprisingly it's working better in IE11 rather than in chrome.
Here is a fiddle
There's a lot of optimization that can be done here. I'll point out a couple.
Starting with the animate function, the first thing I notice is that you're running a bit of code every 10ms. Why don't we check out what's being run?
function animate() {
var string = "აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ ტესტ ტესტ აი ემ ე თეიბლ ტექსტი იწერება აქ"; //string to animate
position = 150; //initial position of string
window.setInterval(function () {
clearLine(0);
drawOnBoard(string, position, 0);
position = position - 1;
}, 10);
}
Clearline is the first function.
function clearLine(n){
for(var i=n*symbolHeight*lineWidth+n*lineWidth;i<(n+1)*symbolHeight*lineWidth+n*lineWidth;i++)
leds[i].style.backgroundColor="black";
}
That's a bit of a mess in the for loop. My understanding is that non-compiled code will run all of that math for every single iteration. So let's move it out of the for loop.
function clearLine(n) {
var initial = n * symbolHeight * lineWidth + n * lineWidth;
var length = (n + 1) * symbolHeight * lineWidth + n * lineWidth;
for (var i = initial; i < length; i++)
leds[i].style.backgroundColor = "black";
}
Ah but there's still more to be done. I see that both equations have a lot of shared math.
function clearLine(n) {
var whateverThisIs = symbolHeight * lineWidth + n * lineWidth;
var initial = n * whateverThisIs;
var length = (n + 1) * whateverThisIs;
for (var i = initial; i < length; i++)
leds[i].style.backgroundColor = "black";
}
I saw that you're moving on so I'll stop working on this for now. There's still plenty more to optimize.
Here's a fiddle of the updated version.

Circle Collision Detection HTML5 Canvas

I want to check if circles are colliding with each other.
I know I can do this by getting a distance between the two centers of the circles and subtracting the radius of each circle from that distance and seeing if 'distance' is > 1.
How can I do this efficiently though with say, 1000 circles? Maybe I can somehow get the nearest 20 circles or something like that and check these? I don't know how I would begin to go about that efficiently though either..
Any ideas?
Here is an example:
http://experiments.lionel.me/blocs/
Before you start calculating exact differences in distances, you can at least compare the x/y positions of the centers v.s. the radii. That information is implicitly available in the circle and requires just some simple comparisons and addition/subtraction.
That'll let you compare the simple distances in x/y between all the circle pairs, and throw away any that are obviously not collision candidates, e.g.
abs(x2 - x1) > (r2 + r1)
abs(y2 - y1) > (r2 + r1)
... if the distance in X or Y between the circle centers is greater than the sum of the radii, then they cannot be colliding.
Once you've whittled down the possible colliders, THEN you do the formal exact cartesian distance, which is where the 'heavy' multiplication/division stuff comes in.
Consider storing the coordinates of the circles' centers in a quad tree, then you would only need to check whether the circle intersects with other circles in that quadrant or adjacent quadrants.
The one caveat is that you need to sure the quad tree's leaf nodes have a minimal diameter of the radius of your largest circle, otherwise you will have to check more than just adjacent nodes for intersection.
http://en.wikipedia.org/wiki/Quadtree
If your circles are well scattered, then a simple optimization you can do is to store your circles sorted on the x or y axis, then you only need to check with circles who's x or y coordinate is within the radius of the circle.
The efficiency is going to be concerned with the speed of the algorithms you are using, for instance the speed of the square root algorithm that you calculate the distance with, and your data structures will determine the efficiency of memory, in addition to algorithms. Another way to speed up the calculations would be to reduce the precision of the distance calculations.
The best method to detect if the circles are colliding is, as you said, to store the circles' center coordinates and radius in variables and compute whether or not the distance between the centers is equivalent to 0 when the radii are subtracted.
I highly recommend Keith Peter's AdvancED ActionScript 3.0 Animation book, where you can find the concrete implementation of Quadtree algorithm in Actionscript.
Here are the basic steps:
First create a two dimensional grid and scatter all the balls randomly across the field.
private function createGrids():void {
_grids = new Array();
for (var i:int = 0; i< stage.stageWidth / GRID_SIZE; i++) {
_grids[i] = new Array();
for (var j:int = 0; j< stage.stageHeight / GRID_SIZE; j++) {
_grids[i][j] = new Array();
}
}
}
Assign balls to grid cells
private function assignBallsToGrid():void {
for (var i:int = 0; i< numBalls; i++) {
var ball:Ball = Ball(_balls[i]);
var xpos:int = Math.floor(ball.x / GRID_SIZE);
var ypos:int = Math.floor(ball.y / GRID_SIZE);
_grids[xpos][ypos].push(ball);
}
}
Check if two balls are colliding in a single cell, then check the balls in adjacent cells. As Charles Ma mentioned the only consideration here the grid cells dimension must be greater or equal to the largest ball diameter.
private function checkOneCell(x1:Number, y1:Number):void {
var _cell:Array = _grids[x1][y1] as Array;
for (var i:int = 0; i< _cell.length-1; i++) {
var ballA:Ball = _cell[i] as Ball;
for (var j:int = i+1; j< _cell.length; j++) {
var ballB:Ball = _cell[j] as Ball;
checkCollision(ballA, ballB);
}
}
}
private function checkTwoCell(x1:Number, y1:Number, x2:Number, y2:Number):void {
if (x2 < 0) { return }
if (x2 >= _grids.length) { return }
if (y2 >= _grids[x2].length) { return }
var _cell0:Array = _grids[x1][y1] as Array;
var _cell1:Array = _grids[x2][y2] as Array;
for (var i:int = 0; i< _cell0.length; i++) {
var ballA:Ball = _cell0[i] as Ball;
for (var j:int = 0; j< _cell1.length; j++) {
var ballB:Ball = _cell1[j] as Ball;
checkCollision(ballA, ballB);
}
}
}
private function checkCollision(ballA:Ball, ballB:Ball):void {
var dx:Number = ballB.x - ballA.x;
var dy:Number = ballB.y - ballA.y;
var dist:Number = Math.sqrt(dx*dx + dy*dy);
if (dist < ballB.radius + ballA.radius) {
// do something
}
}
Here is how it looks like the main method:
private function checkBallsCollision():void {
for (var i:int = 0; i< _grids.length; i++) {
for (var j:int = 0; j< _grids[i].length; j++) {
checkOneCell(i, j);
checkTwoCell(i, j, i+1, j);
checkTwoCell(i, j, i, j+1);
checkTwoCell(i, j, i-1, j);
checkTwoCell(i, j, i+1, j+1);
}
}
}
NOTE:
The code is written in Actionscript but can be implemented quite easily in Javascript.

HTML 5 canvas animation - objects blinking

I am learning ways of manipulating HTML 5 Canvas, and decided to write a simple game, scroller arcade, for better comprehension. It is still at very beginning of development, and rendering a background (a moving star field), I encountered little, yet annoying issue - some of the stars are blinking, while moving. Here's the code I used:
var c = document.getElementById('canv');
var width = c.width;
var height = c.height;
var ctx = c.getContext('2d');//context
var bgObjx = new Array;
var bgObjy = new Array;
var bgspeed = new Array;
function init(){
for (var i = 1; i < 50; i++){
bgObjx.push(Math.floor(Math.random()*height));
bgObjy.push(Math.floor(Math.random()*width));
bgspeed.push(Math.floor(Math.random()*4)+1);
}
setInterval('draw_bg();',50);
}
function draw_bg(){
var distance; //distace to star is displayed by color
ctx.fillStyle = "rgb(0,0,0)";
ctx.fillRect(0,0,width,height);
for (var i = 0; i < bgObjx.length; i++){
distance = Math.random() * 240;
if (distance < 100) distance = 100;//Don't let it be too dark
ctx.fillStyle = "rgb("+distance+","+distance+","+distance+")";
ctx.fillRect(bgObjx[i], bgObjy[i],1,1);
bgObjx[i] -=bgspeed[i];
if (bgObjx[i] < 0){//if star has passed the border of screen, redraw it as new
bgObjx[i] += width;
bgObjy[i] = Math.floor(Math.random() * height);
bgspeed[i] = Math.floor (Math.random() * 4) + 1;
}
}
}
As you can see, there are 3 arrays, one for stars (objects) x coordinate, one for y, and one for speed variable. Color of a star changes every frame, to make it flicker. I suspected that color change is the issue, and binded object's color to speed:
for (var i = 0; i < bgObjx.length; i++){
distance = bgspeed[i]*30;
Actually, that solved the issue, but I still don't get how. Would any graphics rendering guru bother to explain this, please?
Thank you in advance.
P.S. Just in case: yes, I've drawn some solutions from existing Canvas game, including the color bind to speed. I just want to figure out the reason behind it.
In this case, the 'Blinking' of the stars is caused by a logic error in determining the stars' distance (color) value.
distance = Math.random() * 240; // This is not guaranteed to return an integer
distance = (Math.random() * 240)>>0; // This rounds down the result to nearest integer
Double buffering is usually unnecessary for canvas, as browsers will not display the drawn canvas until the drawing functions have all been completed.
Used to see a similar effect when programming direct2d games. Found a double-buffer would fix the flickering.
Not sure how you would accomplish a double(or triple?)-buffer with the canvas tag, but thats the first thing I would look into.

Categories