Leaderboard


Popular Content

Showing content with the highest reputation since 04/24/19 in all areas

  1. 2 points
    Exca

    Redrawing only when needed?

    I have a method where I have two different changes that can happen in the scene. Tweens and handlers that get run every frame. For tweens I check if amount of active tweens creater than 0, then it means that something is changing. For onrender-handlers I have a custom component that allows for components to register themselves to get onrender -events and their return value will tell if something has updated. If either tween has updated or any of the components requires rendertime, then that frame is rendered. Otherwise no render will occur. In some cases this can be improved by splitting the scene into multiple canvases. One that gets updates rarely and one that holds the actual gameplay and is updated frequently. Though using that method is something that should be clearly thought out beforehand or you'll end up with multiple canvases to render each frame. Having render loop stop completely is something that you shouldn't do. As calling requestanimationframe is really cheap and not worth the trouble to build a mechanic with renderloop cancellation. Easier to just skip rendering on frames that dont need it.
  2. 2 points
    Anchor and Pivot are your friends. If you don't wish to use them because you want to maintain left alignment then consider using a child Sprite, or other arrangement of Containers. Then you can freely adjust the anchor (or pivot) of any child, do the transformation as would be intuitive and the parent will be unaffected. There is minimal overhead in using children and they can improve code readability and maintenance. The alternative (using a single Sprite) involves translating (x=-width) before the flip (scale.x*=-1) or rotation, then translate back again when done. It's unlikely to feel as intuitive - and is likely more prone to mistakes or confusion later?
  3. 2 points
    Gio

    Cardlings, a digital board game

    Hi everyone I've made a tactical strategy game (single and multipalyer) with the help of some very talented people, including some active users of this forum too. The game will be availble on Steam from June 5th for Windows, MacOs and Linux. Android and iOS versions will follow. Please check out the Steam page or the game's official site for more info. The game was made with our own game engine (WADE) which is free to use if you want to make your own games with it. I'll be writing some blog posts about the development of the game (what went right and what went wrong) as soon as I get a chance.
  4. 2 points
    Does this help? https://www.pixiplayground.com/#/edit/sNKLacqLJenYpsQyc6mIp The issue you were struggling with is that Text is lazily updated. It only usally gets updated when it gets rendered; but you can force it to update with the updateText() function.
  5. 2 points
    Hello, I'm creating a front end for a graph display application. It displays a sort of fancy force directed graph, so there are nodes and lines. I'm using pixi-viewport to contain my main scene so it can be zoomed/panned/culled. Once you zoom in past a certain limit the nodes will start to display a text label across the center. I'm using PIXI.Text for these as I don't control what characters will be displayed. I want the text to look crisp so I'm willing to take the hit of generating new text textures on each zoom action. This isn't too expensive as you have to be so far zoomed into to activate the labels that there isn't to many of them on screen at one time. The problem I have is the the text is inside a container that has the hierarchy for a graph node, its shadow/outer selection, inner ring, icon etc so it inherits the world transform for scale and it causes the text to scale and then look bad. I don't want the text to scale as I regenerate it at a suitable text size each zoom to look perfect. I tried the naive solution of trying to apply an inverse 1/parent-scale which sort of works some of the time but not really. I tried putting the text on a layer above the viewport and manually positioning them and resizing them, this worked perfect till I dragged one node over another and realised z-indexing is broken now that they aren't drawn with the rest of their node display objects. Does anyone know if there is a way to stop the worldtransform from applying to a child/child container? I'm currently considering creating my own container subclass that somehow sets the world transform to identity and just position its local x,y at world co-ordinates inside the viewport, this container will be added into the node hierarchy and contain the text item. I'll need to browse through the code a bit to see how. But I'm not sure if it is possible, even a good idea, or complete madness.
  6. 2 points
    Yes, there is! Here's an example of Shockwave that you could include w/ a `<script>` element. https://cdn.jsdelivr.net/npm/@pixi/filter-shockwave@3.0.1/dist/filter-shockwave.js All filters are published to NPM with bundler file versions ("lib" folder) and a browser version ("dist" folder). You can use jsdelivr or other CDN that allows you to include files from published NPM versions.
  7. 2 points
    jonforum

    Line of sight triangles in v5

    It reminds me of what has been implanted in this game. https://ncase.me/sight-and-light/ I suppose that you have already got your hands on these articles, I share them in case. it in canvas no pixi but it will be cool to see this in pixidemo ! a codepen ** https://codepen.io/xno/pen/YOQZzw https://codepen.io/pandaec/pen/rzxYNB a jsfiddle ** http://jsfiddle.net/nLMTW/ http://jsfiddle.net/s2un50dp/ Shadertoy ** best performance i think https://www.shadertoy.com/view/4dfXDn Some code for do it in a shader GLSL https://stackoverflow.com/questions/34708021/how-to-implement-2d-raycasting-light-effect-in-glsl and a very good article https://www.redblobgames.com/articles/visibility/
  8. 2 points
    Exca

    creating a animated soft color

    You can do that with vertex shader by giving each vertice a color and then gpu interpolates between those points. Or you can do the calculation in fragment shader to get more refined look. Here's an example how it could be done with fragment shader https://www.shadertoy.com/view/tls3zS For info on how the color palette is done read this article http://www.iquilezles.org/www/articles/palettes/palettes.htm
  9. 2 points
    khleug35

    Space Shooter J Hit

    Hello Everyone. My new HTML5 shoot em up game made using Panda2 This game can play on mobile or desktop, but this game is no sound yet. Special thanks to @enpu, @Stephan and @Wolfsbaneteaching me coding skill, really thanks This game can play on mobile or desktop Try the game in here , hope you enjoy: https://superfranco.itch.io/space-shooterjh Android Version: Google Store Link ScreenShot: How to Play? For desktop control W key - Up A key - Left D key - Right S key - Down P Key - Pause the Game Space - use subweapon For Mobile control You can control the ship movement with JoyStick Click or press the icon to use subweapon and Pause the game. You can destroy the enemy and get money to buy a new ship and upgrade them. Mega Bomb - Mega Bombs damage and clears all forms of the enemy from the screen. When upgraded to level 3 or above,it can also clear enemy gunfire or bullet. Laser - Laser allows you to deal massive damage onto your enemies. Energy Shield - Energy Shield can protect player, When upgraded, it improves the duration of the shield. Mobile version. Android This is a classic vertically scrolling space shoot 'em up game. It has 9 levels with Easy and Hard unlocking regimen. The Hard mode can make double the amount of stars as your reward. You can go to store to upgrade your ship and buy a new ship. How to play -Control the ship movement with JoyStick -Click the icon to use subweapon and Pause the game. Item- Coin - Dropped from enemies , you can take this to upgrade your ship and buy a new ship. Health - Heals 20% of your ship. Subweapon item - increase one Subweapon amount of use. SupWeapon Mega Bomb - Mega Bombs damage and clears all forms of enemy from the screen. When upgraded to level 3 or above,it can also clears enemy gunfire or bullet. Laser - Laser allows you to deal massive damage onto your enemies. Energy Shield - Energy Shield can protect player, When upgraded, it improves the duration of the shield. Ship upgrades are Attack -power of bullets from main cannon. Speed - speed of ship. Health - endurance of the ship. SupWeapon - increase your SupWeapon power or improves the duration of the shield. If you clear all the stage with Hard mode. You are successful to complete the game. Made With: https://www.panda2.io/
  10. 2 points
    If you don't need gradients, there is this clever 3 sprites approach :
  11. 2 points
    themoonrat

    PIXI Interaction Touch

    You rang, m'lord? @JECKL try looking at `renderer.plugins.interaction.eventData.data.global` instead
  12. 2 points
    We are working on full example for playable ads with hacks for pixi loader that allow to bundle everything including Spine models into one file . You can either wait 2-4 weeks or do it yourself.
  13. 1 point
    I am creating a game, where a lot of tiles need to be rendered. My goal is to render with this method at least 500k tiles. Since the tiles won't be redrawn every time but moved, this method should work out. I am using the pixi-tilemap library to create a fast & simple renderer to render a dynamic tilemap. The renderer approves itself to work, but .position.set seems to pull the tilemap from the interface away. I know, the function .position.set does not contain the same parameters as the one of the demo, however this function also does not work with the parameters of the demo. Some parameters must be added. The tutorial I have been using this classic demo: https://github.com/Alan01252/pixi-tilemap-tutorial
  14. 1 point
    I have updated the pixi tilemap renderer. However it seems that the the .addFrame function has some sort of limit, as it displays at a certain point only a specific amount of tiles. Ivan, can you check the renderer, if I am not wrong please. Fully working renderer: https://github.com/StephanHQ/PIXI-Tilemap-Renderer
  15. 1 point
    ivan.popelyshev

    Redrawing only when needed?

    Yeah, I also used double-canvas and triple-canvas on slow devices, browser compositeLayers works better than webgl or 2d in that case. Thought i recommend to have only one of them as webgl..
  16. 1 point
    Hello, I'm trying to optimise at bit my text rendering. I render a graph, and each node in it contains an icon (from fontawesome or similar type font) and the link connecting it can display the relation name. There is only 9 possible icons and 13 relations so it seems like a bad idea to generate 'N' PIXI.Text objects so I thought I'd try just caching the text object in a map and using its texture inside sprites then cleaning up when done. I've ran into two problems though. First the texture wont display unless the text is part of the scene. If I add it as a child the Sprites will work. If I don't they will just be empty. Secondly, if I try to work around problem one by adding the text into the scene anyway the Sprite versions will all flicker when the text is changed (I change the text on a zoom event to scale it sharply) and not appear for a starting frame when the text is added. Is there a way to generate the texture for a text item without adding it to the scene, and could that fix the flicker? I forked someone elses pen to try demonstrate the text being part of the scene issue. https://codepen.io/anon/pen/yWXMJM I did see this project - https://github.com/JiDW/pixi-cocoontext/blob/master/src/CocoonText/index.js But I was hoping not to have to copy all the inners of Text Cheers Bob
  17. 1 point
    A running playground that reproduces this problem would be really helpful for trying to track down what is going on here. You can choose the pixi version using the "settings" button to get your exact version.
  18. 1 point
    Hi Ivan, thanks for your reply! I have been debugging (extensively) and it seems the error was caused by some odd state of package-lock.json of npm, or some strange dependency issue. Deleting that file (also did for yarn.lock), plus all the modules, and starting from scratch to install all the dependencies seemed to make the trick. I did not even think of this option, but after your message saying that it should all work fine, I created some basic test with a new fresh project and I realized everything was just working fine. Perhaps this post can help anyone who bumps into a similar problem. Thanks again and sorry for the mess!
  19. 1 point
    First... Just move the sprite container left 10 pixels, then it's children will all move with it. Second, avoid creating functions every frame. Use a basic for loop, or create a function that's reused. But don't create a new anonymous function every frame for within a forEach. You do that everywhere and the garbage will add up quickly.
  20. 1 point
    Ah. Thank you! Turned out that in addition to this, the pixi-viewport library was overwriting all filters for me. After inspecting it's code it turns out that David's viewport is messing too much with PIXI objects. I probably need to write my own simple viewport... Thank you for your help!
  21. 1 point
    its not an edge case, sometimes just one resource can fail, depends on what server or service do you use. If its a problem for your users, make a fallback, for example you can start downloading everything again
  22. 1 point
    Howdy! Brand new to Pixi.js and JS development in general. I have a quick question regarding InteractionManager. I have two objects on the stage: a box with a scroll listener for mousewheel events and multiple boxes "underneath" with pointertap listeners. Is there a way to capture these scroll events and the pointertap events on the objects underneath? The current behavior is.. the scroll events are fired, but because that scroll box is interactive and above the click boxes, the pointertap events are not fired. Any thoughts? Thanks in advance!
  23. 1 point
    jonforum

    PixiJS Tutorials or video courses

    hi, did you try filter with google video with pixijs ? I made you a link tag include video filters for french, english, russian ... i don't know your natal language ? You have a lot of video in those 3 language. Maybe also try add spanish , china and korean... it should work, here https://www.google.com/search?q=pixijs&lr=lang_en|lang_fr|lang_ru&newwindow=1&tbs=lr:lang_1en|lang_1fr|lang_1ru,srcf:H4sIAAAAAAAAACXIQQ6AIAwF0duwMWHngSr9QaKlSSk23t4Ed_1Nme3X6PJCLSvJo7rDVp8u9VxIwnrEORQQZ_16gG9KHlWirKEHRXy03TB2f94ZtUAAAA&tbm=vid&source=lnt&sa=X&ved=0ahUKEwiF4N2axZviAhXyV98KHVSGAskQpwUIIA&biw=1502&bih=750&dpr=1.25 you can affine filter with some tag like, `start`, `tuto`, `intro`, `node` ... book i know only french https://ecitydoc.com/download/prendre-en-main-pixijs-1-posons-les-bases_pdf english https://www.amazon.com/Learn-Pixi-js-Create-Interactive-Graphics/dp/1484210956 https://www.pixijs.com/tutorials
  24. 1 point
    bigtimebuddy

    Safari Cleanup Issue

    In this case, for SPAs it’s better to not destroy your renderer. You can destroy the display objects (sprites, textures, etc), but keep the reference to your canvas and renderer (make sure you pause the ticker). There’s a limit to how many webgl canvases you can create simultaneously. Better to not continually create and destroy. Maybe there’s some GC trick for Safari, but this has been my standard practice working with virtual dom frameworks.
  25. 1 point
    Hello! I have a square picture,Now I want to cut this picture into a hexagonal picture without using photoshop. Is there any good implementation idea? mask?or frame?
  26. 1 point
    I want to restrict the size of the applied filter on canvas. In the below codepen i have set the displacement filter and moving it according mouse position. But the problem is it's covering entire background. I want to fix the size of the filter. I'm new the Pixijs and any help is appreciated. https://codepen.io/ajitcj/pen/yWOaaY
  27. 1 point
    Umz

    Link It Up!

    Brilliant game! Love the sound effect when he falls onto the spikes. Really get a feeling for the pain haha 😁
  28. 1 point
    Damn it last time you said you are working on an example for playable ad, you said its gonna be done in 2-4 weeks. And that was 2 weeks ago Ok well here we go me trying to make the spritesheet work UPDATE: It works. Apparently you have to call spritesheet.parse(()=>{}) yourself, which I didnt know (Parse takes a callback). And the meta data of the json, does not need any field for image.
  29. 1 point
    I've made a fork and changed keydown handler a bit https://plnkr.co/edit/EPyxbRDmSg0tstD5Q55h let me know what you think about it.
  30. 1 point
    Its cool that you used WebGL for this, and the code is easy to read. Nicely done. I found bug in this example. When snake length is greater than 1 and its moving right when you press up arrow and then left arrow the game resets.
  31. 1 point
    Too bad that the forum was down for so long... anyway I peeked at the problem that Ivan encountered in his V5 demos, and found out that syncUniformsGeneration function generates empty function (full story can be found here). Having done that I went back to v4 and got the thing working, with one little caveat that I feel like is worth mentioning. When testing out filters I found out by default the last shader is set active.So if you have multiple shaders setup, you'd have to manually "activate" appropriate shader before writing to uniforms, otherwise webgl would swear at you in console with red errors. In order to do that, however, you'd need access to shader created by this line (cached one will also be fine) 19478: shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); However, it is a local variable of FilterManager's applyFilter function, so I ended up using this monstrocity as a workaround PIXI.InjectedApplication = class InjectedApplication extends PIXI.Application { constructor({width = arguments[0], height = arguments[1], options = arguments[2], noWebGL = arguments[3], sharedTicker = arguments[4], sharedLoader = arguments[5]}) { super(width, height, options, noWebGL, sharedTicker, sharedLoader); var oldSyncUniforms = this.renderer.filterManager.syncUniforms; this.renderer.filterManager.syncUniforms = function(shader, filter) { //shader is NOT of type PIXI.Shader but of _Shader2 ! //Call "vanilla" sync uniforms oldSyncUniforms.call(this, shader, filter); //Then call custom one if(filter.syncUniforms) { filter.syncUniforms(shader); } //Save references to filter //in order to be able to switch active shader. filter.__program = shader.program; filter.__shader = shader; }; } updateShader(shader, func) { //this.shaders is just a map of PIXI.Filter shaders let shdr = this.shaders[shader] || shader; let prev = this.renderer._activeShader; this.renderer.bindShader(shdr.__shader); //Make shader use program (openGL terms) func(shdr); //Execute function app.renderer.bindShader(prev); //Bind previous original shader back } } And the use example is simply this: function mouseMoveHandler(e) { let newpos = e.data.getLocalPosition(app.stage); app.updateShader('squareshader', function(shader) { //_uniforms are my custom uniforms and squares is array of structs in GLSL shader._uniforms['squares[0].coords'] = new Float32Array([newpos.x, newpos.y]); }); } Thank you, I already knew that. To my knowelage this also applies to arrays, ex. struct SomeInfo { vec4 color; }; uniform SomeInfo c[2]; to access 1st color the correct string for position getter would be "c[0].color"
  32. 1 point
    Exca

    Line of sight triangles in v5

    I have done similar thingie with v3, though it was heavily optimized with assumptions about what kind of lights there were, what was the world size etc. What I did in short was this: - Build a texture (2048x2048) with all the shadow casters in it. - For each light, do a raycast to 512 directions (on gpu) and build a 1x512 texture with each pixel value telling how long the light can go from that point. - Render lights using that texture (calculate angle, check if distance is over the value in texture, if it is, ignore pixel, otherwise draw light with light settings). - Draw lights into a single texture and blend that with diffusetexture. - Split the lights into static & dynamic groups for performance. That solution also included normal mapping but in this case that's not needed. Maximum world size was 2048x2048 in this case, as everything had to fit inside a single texture.
  33. 1 point
    Hi, Im trying to make a simple app/feature, that fills an area with random pixels(random color at random time) I have a working solution that is only a handful of lines of code, but its crazy slow. (uses WegGL and Nvidia GTX1060 gfx card + i7 cpu ). The way i fill the canvas with random pixels at the moment is like this: 1) set interval that calls the drawRandomPixels function( it struggles to draw 1 frame every 250 ms ) 2) loop over every pixel coordinate(x, y) and use this.contentGfx.fillColor = 0xFFFFFF * Math.random(); this.contentGfx.drawRect(x, y, 2, 2); 3) after all the pixels have been looped over, call the endFill() and render the stage. Very simple and basic, yet it has massively worse FPS than what i get when i play Battlefield 5 on highest settings. The area that im trying to fill is 250 x 250 canvas. I used 2x2 pixel size to get a bit better performance but its still damn awful. Is there a better way to draw pixels in PIXI ?
  34. 1 point
    Pixijs has no access to text geometry. We need something like opentype.js to do that. Currently there are two three text plugins for pixi v4: pixi-sdf-text (prerender bitmapfont), pixi-richtext (gen sdf by canvas in runtime) and pixi-ui (no docs, helpful author, just better bitmaptext) There is opentype support in our roadmap, thank you for pointing out one more source that we can look at!
  35. 1 point
    RagingPixel

    Google Web Toolkit (GWT)

    Google Web Toolkit (GWT) is awesome in my opinion. I made simple mini game in Java and it works perfect in browser. Im looking into LibGdx project too - it uses GWT for compiling game into HTML5. https://libgdx.badlogicgames.com/
  36. 1 point
    DrSnuggles

    JavaScript nested array stumper

    yes, init of the new object in the array is important. It's important because later you want to access gear.something and gear has not yet been created. That's where the error is coming from. JS can not DIM an array from begin like it is possible in other languages. You can DIM with var myArray = new Array(20) but this just creates empty entries and not objects, so you cant set the property "cost". Have look here: https://www.w3schools.com/js/js_arrays.asp var myArray = []; Dim(myArray, 20); // maybe you like this more than the for i=0;i<myArray.length;i++ loop for (key in myArray) { myArray[key].cost = 20; } // another way to fill it myArray.forEach(setDmg); console.log(myArray); // shows filled array function Dim(arr, size) { for (let i = 0; i < size; i++) { myArray.push({}); } } function setDmg(entry) { entry.dmg = 10; } Working with the good old arrays is absolute no problem and a clean way to do that. Try to make it easy for you to understand that code again if you dig it out in some years.
  37. 1 point
    Hey @vsudakov Take a look at https://jsbin.com/nikikirova/edit?js,output Best regards,
  38. 1 point
    I will look at it today or tomorrow, but there's something i can mention right now : I'm working on new tutorial , https://github.com/ivanpopelyshev/pixi-starfighter , and it has a tilemap based on v5 graphics. You can use the same algorithm for pixi-tilemap. In fact im gonna use the same algo for pixi-tilemap v5 tutorial when I start it. You already have something like that but I'm not sure that everything is correct. For example, im not sure about "tileset.position.set(startCol,startRow);" maybe you need *scale there
  39. 1 point
    DrSnuggles

    JavaScript nested array stumper

    [] = array {} = object That's right and important this here works. I'm doing hard finding the prb without weaponsList. var weapons = [ { name: "Knife", rank: { damagePerClk: 2, cost: 1, }, }, { name: "BFG", rank: { damagePerClk: 9999, cost: 500, }, }, ]; for (var i = 0; i < weapons.length; i++) { console.log("Name: "+ weapons[i].name); console.log("damagePerClk: "+ weapons[i].rank.damagePerClk); console.log("Cost: "+ weapons[i].rank.cost); } it looks like you want to init your weapons in the initGame function. several way to do that. var weapon = []; var weaponList = ['Knife', 'BFG']; var spell = ['Light', 'Fireball']; function initGame() { var wLength = weaponList.length; var sLength = spell.length; for(let i = 0; i < wLength; i++) { weapon[i] = {}; // this is important, creates an object in weapon array weapon[i].name = weaponList[i]; //spell[i].name = spellList[i]; console.log(weapon[i].name); } } function initGame2() { var wLength = weaponList.length; var sLength = spell.length; for(let i = 0; i < wLength; i++) { // push the full object weapon.push({ name: weaponList[i], anotherKey: 0.666} ); console.log(weapon[i].name); } } function initGame3() { var wLength = weaponList.length; var sLength = spell.length; for(let i = 0; i < wLength; i++) { var tmp = {}; tmp.name = weaponList[i]; tmp.foo = "bar"; weapon.push( tmp ); console.log(weapon[i].name); } } hope this helps you.
  40. 1 point
    xRa7eN

    JavaScript nested array stumper

    OK, I think i have "BASIC" understanding.. Let me know if this is correct: So a "bracket" is used to make the basic traditional array game [] which will give game[0], game[1] etc... correct? Braces will give an object? game{}, so game {name: coolplayer, hp:10} which yeilds game.name // coolplayer? then to combine, make your arrya first? then put in anything you want, but if you want another array, you use brackets again - like so? game [ player[{name:'george', hp:25}]] then I can pull it as such: game[3].player[2].name // george So do I have the gist of that? Seems to work when I test it. Totally not like arrays I am used to LOL, but unique and more flexable So... when i get to this: weapon = [ { name, rank:[ {damagePerClk, cost} ] } ]; works fine if i manually insert data, but if I loop as shown below: function initGame() { var wLength = weaponList.length; var sLength = spell.length; for(let i = 0; i < 14; i++) { weapon[i].name = weaponList[i]; //spell[i].name = spellList[i]; console.log(weapon[i].name); } } crashes. Says "i" is not defined, but that is not the issue. and stops at 1. (example, log shows 0,1 crash). "i" is fine, and if i loop through a list - (spellist for example) it list all my spells as they are. I am guessing it is how I have weapon defined (declared). Right?
  41. 1 point
    Stephan

    RESOLVED: graphics hires problem

    I just had another look at the problem and I think it is a small bug in the engine. I just posted a pull request for the develop branch to fix the problem.
  42. 1 point
    If there's no rotation involved making a spritesheet parser for any tool is very easy even for people who hate math. It comes usually with a xml or json that lists frames with position, dimension, and names. You extract those names in a loop, create rectangles out of position/dimension, put everything in a dic and voila, now you can run another loop to create texture from the main texture and pass along those frames(rectangles) you created when parsing. NO MATH involved.
  43. 1 point
    The issue is your bundler. When you add non-standard things to your 'regular' JS, you can't expect perfect interoperability with JS libraries (such as Phaser) which expect you to write in JS. The issue lies with however your bundler transforms `./assets/button.png`, usually, this will become a file path, which would work fine if, and only if, the paths are correct. I am going to guess that in your case, they are not correct, hence the 404. More strangely, it doesn't even try to insert a path, just the variable name, which either means you're calling Phaser functions wrong, or, the bundler is really mucking you around. Most bundlers that allow you to import asset paths also will handle packing those assets and they _should_ also handle serving it for you in the same way they're serving your HTML and other static code assets.
  44. 1 point
    grelf

    2D Map Representation as 1D array

    I have managed to rewrite my scene drawing (in www. myforest.uk) so that it does not reallocate two huge arrays and fill them with freshly created objects every time. This rewriting reduces the scene drawing time by about 30%. There is also less variability in the time taken from one scene to another which tends to confirm that garbage collection and reallocation were taking a lot of the time. Reallocation would be variable because it depends so much on what contiguous chunks of memory are available. I have written the following to show some things that developers may need to consider in their own code. My terrain is generated by a function of (x, y) position (in fact a method of an object of type Terra). It is a complicated function so it does not want to be done repeatedly for each position; instead its results must be held in arrays for subsequent reference during scene building. Two big arrays hold the results of that around the (moving) observer's current position to enable the scene to be drawn. For each position the arrays refer to an object of type ScenePoint which contains the distance and bearing of the point from the observer and other things (such as terrain details and amount of fogging for distant points). Each ScenePoint object has 10 properties so requires at least 80 bytes, probably more like 100 bytes allowing for the Object structure itself (I think that varies from browser to browser). One of the big arrays, around [x][y], goes out to the current view range which is user-selectable and can be up to 400 meters, so the array may have to be 801 x 801 to surround the observer. This is now allocated at the start of the program. Each array value will be a reference to a ScenePoint object so the array itself takes 8 x 801 x 801 = 5.1 megabytes. Then the 801 x 801 ScenePoint objects, also now allocated once at the start instead of freshly in each call to Scene.draw (), occupy about 100 x 801 x 801 = 64 megabytes. Another array, ahead , contains references to the same ScenePoint objects but is sorted during scene drawing so that the most distant points come first. This array does not contain references to objects behind the observer and so it is allocated as new Array (400 x 801). It requires a mere 8 x 400 x 801 = 2.6 megabytes. So my latest version of The Forest, v19.4.10 (see www.myforest.uk ) allocates just over 70 Mbytes when it starts and then no longer has to reallocate this (in many pieces) every time a scene is drawn. I still find it remarkable that my scene drawing is done in a couple of seconds even for the 400 metre horizon range. During that time the 'ahead' array is sorted too! When starting to draw a scene 'ahead' has to have all its elements set to undefined because as the observer moves and turns a varying number of points can lie ahead. I rely on the specification for Array.sort() which says that undefined elements get sorted to the end of an array. To support all this I have written a new JavaScript file to create one object of type Around. People may be interested to see it (below) but first Matt: Having made this change it was then easy to experiment with making 'around' a 1D array instead of 2D, calculating the index from x and y myself. I found no difference in performance (in FireFox). // Part of The Forest www.grelf.net (www.myforest.uk) // Copyright (c) Graham Relf, UK, 2019 /** One object of this type is constructed at the start to avoid reallocating * big arrays every time a scene is drawn */ function Around () { var el = document.getElementById ("range"); this.aMid = 0; // The middle index of each x/y array // Find largest range user may select: for (var i = 0; i < el.options.length; i++) { var r = parseInt (el.options .value); if (r > this.aMid) this.aMid = r; } var wd = 2 * this.aMid + 1; this.aheadChange (this.aMid); this.around = new Array (wd); for (var x = 0; x < wd; x++) { this.around [x] = new Array (wd); for (var y = 0; y < wd; y++) { this.around [x][y] = new ScenePoint (0, 0, 0, 0, 0); } } } /** Use at the start of drawing a new scene * NB: mex, mey are rounded observer coordinates */ Around.prototype.init = function (mex, mey) { this.xOffset = this.aMid - mex; this.yOffset = this.aMid - mey; // Clear previous scene: for (var i = 0; i < this.nAhead; i++) this.ahead = undefined; this.nAhead = 0; }; /** Only used if user changes the range (and in Around constructor) */ Around.prototype.aheadChange = function (range) { this.ahead = new Array (2 * range * range); this.nAhead = 0; }; /** Add a ScenePoint object reference to the scene ahead */ Around.prototype.aheadPush = function (sp) { this.ahead [this.nAhead] = sp; this.nAhead++; }; /** How many active ScenePoint objects are currently ahead */ Around.prototype.aheadLength = function () { return this.nAhead; }; /** Get a reference to the ith ScenePoint object ahead */ Around.prototype.aheadGet = function (i) { return this.ahead ; }; /** Sort the ahead array in descending order of distance */ Around.prototype.aheadSort = function () { this.ahead.sort (ScenePoint.prototype.sort); }; /** Get a reference to the ScenePoint object at (x, y). * This is so that extra properties can be added to it. */ Around.prototype.aroundGet = function (x, y) { return this.around [x + this.xOffset][y + this.yOffset]; }; /** Set the fields of the ScenePoint at (x, y) as if freshly constructed */ Around.prototype.aroundSet = function (distance, bearing, x, y, odd) { var sp = this.around[x + this.xOffset][y + this.yOffset]; sp.fogNo = 0; sp.tr = undefined; sp.building = undefined; sp.drawn = undefined; sp.clear = undefined; sp.d = distance; sp.b = bearing; sp.x = x; sp.y = y; sp.o = odd; }; Note that in my previous version of Scene.draw () each ScenePoint object was freshly constructed and subsequently might or might not get extra properties added (such as .tr or .drawn). That was poor practice really. For easier maintenance it should be clear in the constructor as to what properties an object can have.
  45. 1 point
    trevordev

    AmmoJS support

    Hey, AmmoJS physics plugin has been added to Babylon preview. It should work well with composite meshes which we've had trouble with in the past with other engines. Let me know if you find any issues or have any feedback. Note: Support for motors, soft bodies, other ammo specific features are not yet supported so yell if you need anything specific for your project. vid.mp4 Examples: Basic impostors: https://playground.babylonjs.com/#7149G4#31 Loading mesh and colliders from file: https://playground.babylonjs.com/#66PS52 Loading and adding colliders manually in Babylon: https://playground.babylonjs.com/#FD65RR Loading and adding collider with joints and pointer interactions: https://playground.babylonjs.com/#DGEP8N WebVR grabbing and throwing: https://playground.babylonjs.com/#ZNX043#1 Docs: https://doc.babylonjs.com/how_to/using_the_physics_engine
  46. 1 point
    Hey Guys! Yesterday I released a free PICO-8 tileset, free for everyone to use, so grab it! https://s4m-ur4i.itch.io/pico-8-pixelart-free-tiles If you like it, check out my other projects, I just released a big Metroidvania / roguelike / platformer Tileset: https://s4m-ur4i.itch.io/2d-metroidvania-tileset-16x16 Everything is low cost because of Indies Check out everything: https://s4m-ur4i.itch.io
  47. 1 point
    SinhNQ

    Combine Babylon.js with Pixi.js

    Hello, * Introducing a bit of pixi.js: pixi.js has full webgl support, a best framework for 2D game with rendering very fast. Would be great if you want make UI game with pixi.js and combine with babylon.js. (Will I get paid for advertising? NO..🤣) Demo babylon.js + pixi.js : https://jsfiddle.net/y5q7Lb1v/21/ This is a perfect duo for your web game world, which you can create high quality games. 😁 Moreover, you can also use GSAP for creating high-performance animations. Demo babylon.js + pixi.js + GSAP lib: https://jsfiddle.net/y5q7Lb1v/28/
  48. 1 point
    mattstyles

    TypeScript vs JavaScript?

    Type correctness is a fallacy, and can not be implemented into a dynamic language without injecting into the runtime, which typescript does not do (although alternatives like flowcheck and some other libs for implementing flow do, it still does not make type checking a silver bullet). Much more info in this article. Having worked with it for an Angular 2 build (which was a horrific experience coincidentally) I can say that using TS creates so many headaches. Importing simple modules becomes an issue and often breaks your build, do you really want to spend half and hour importing a module you want?? Totally bonkers, it should just be a few keystrokes, a bit of network, and boom, get coding. I continually found inaccuracies in documentation as implementations changed which was a pain. I was worried about how TS performs some of its transforms without producing a horrible tangle of inefficient code, turns out that does happen, although a lot of people do work on making these transforms as efficient as possible, its just that some patterns are either not needed or don't work well in a dynamic language. There is also a barrier for every other JS dev, you force them to use TS and not everyone will want to do that (this depends on your project though). The additional killer is that TS is not spec, whilst a lot of what it started considered spec, and certainly its implementation helped the spec to evolve, its a worry. Every time you move away from spec (like Webpack does with modules) you are at risk of moving further away from your chosen language, which is crazy, if your language doesn't support the stuff you want to do then choose another, don't mutate your language beyond recognition, as a web dev you are in a position of luxury here because if the web is your chosen platform then its JS so everything has a pipeline to output JS these days. Typing is useful for large teams as it can make the code easier to understand, but I could dispute this by saying that it introduces a load of clutter and types can be gleaned by a bit of inline documentation, although you wouldn't get static checking (but, see the earlier link, static checking won't secure your program, to the point where it could be pointless). On that, the number of times in TS code I've seen the type specified as <any> because devs haven't put enough effort in (or ran out of time, or, sometimes, been forced in to it because typing is square peg round hole for JS) is shocking and clearly unhelpful. Having said all this, it is gaining popularity so its certainly worth checking out, particularly if you're fond of strongly typed languages (just remember JS is not, and without killing your performance nothing will make it so). Nothing can get you away from this, despite the newer ES2015 class syntax, JS is NOT a classical language. The class syntax is simply sugar around creating a class-like abstraction in a prototypal world. There is nothing superior about OOP or classes, it is simply a different style/flavour/design choice. The reason I bring it up is that if you keep up with a mindset that one thing is superior over another you will overlook anything you deem inferior which means you won't learn its pros/cons and you'll get stuck in your superior world even when you start working on something where that does not make sense. Feel free to ignore, but I'd be wary of pigeon-holing yourself or your tech choices. Learn it all and learn when each different thing makes sense and when it does not. Particularly in the fast-paced JS world, something only remains superior for 6 months, so unless you want to become a dinosaur, keep moving!
  49. 1 point
    eran

    Pausing a Javascript game on incoming call

    I use game.onPause.add(myPauseFunction) but this does not detect an incoming call. I'm doing a race game in Phaser and would like to pause the race on incoming call. any idea how to get this event on Phaser / JS?