Jump to content

Search the Community

Showing results for tags 'Functions'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • HTML5 Game Coding
    • News
    • Game Showcase
    • Facebook Instant Games
    • Web Gaming Standards
    • Coding and Game Design
    • Paid Promotion (Buy Banner)
  • Frameworks
    • Pixi.js
    • Phaser 3
    • Phaser 2
    • Babylon.js
    • Panda 2
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
    • GameMonetize
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered
    • Marketplace (Sell Apps, Websites, Games)

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Twitter


Skype


Location


Interests

Found 19 results

  1. Hi everybody, i want to know what Babylon can do what Unity can't do and vice versa. This is not about which tool is better like "babylon is for web-development and using less ressources and unity is programmed with C#", but more about the functionality of the tools. Are there special functions that can be mentioned? For example: Unity has the function NavMeshObstacle for objects to avoid by AI agents. Does Babylon has a similar function? I ask this with the background thoughts of a multi-agent system which should be built, which I already mentioned in a thread: http://www.html5gamedevs.com/topic/37290-the-question-about-multiple-scenes-again/ As part of my work, I'd like to compare the capabilities of these tools through their API (Babylon: https://doc.babylonjs.com/api/ Unity: https://docs.unity3d.com/530/Documentation/ScriptReference/index.html ) (the only way I can think of to compare functions) and, of course, I don't want anyone else to do my work, but I thought if anyone already had the knowledge, I could use this approach. I hope this kind of question fits in this forum. Thanks in advance.
  2. Hey, I am not great with Babylonjs, but have managed to put together a few timesaving functions. I am sure you have too. If you have any that you thought were clever, please share them. None of mine are clever, but they are useful. Here is the humblest of all to get the ball rolling. All it does it output to the console for development. But once you go into production you can turn off all the console messages by commenting out one line instead of hundreds or thousands. function log(msg) { console.log( msg ); } I set and get global values with the following. There may be a better way but this is how I store player login information instead of using PHP sessions. function setGlobal(varName, varValue){ var global = $( "body" ).data( varName, varValue ); return global; } function getGlobal(varName){ var global = $( "body" ).data( varName ); return global; } function removeGlobal(varName){ $( "body" ).removeData( varName ); } Three more utility functions you may find helpful //converts from degrees to radians function degreesToRadians(degrees) { return degrees * Math.PI / 180; } //converts from radians to degrees function radiansToDegrees(radians) { return radians * 180 / Math.PI; } function deleteAllMeshes(scene){ console.log(scene.meshes.length + " meshes detected"); var countMesh = 0; for (var i = 0; i < scene.meshes.length; i++) { scene.meshes[i].dispose(); countMesh++; i--; } console.log(countMesh + " meshes deleted"); } Here's a way to format a date so it has leading zeroes with numbers under 10. Otherwise the width of the output will jump around. Remember to use a monospaced font. function formatDate(d){ function pad(n){return n<10 ? '0'+n : n;} function pad2(n){ if (n < 10) return '00'+n; else if (n < 100) return '0'+n; else return n; } return d.getFullYear()+'-'+ pad(d.getMonth()+1)+'-'+ pad(d.getDate())+' '+ pad(d.getHours())+':'+ pad(d.getMinutes())+':'+ pad(d.getSeconds())+'.'+ pad2(d.getMilliseconds()); } Calculate distance between meshes? function getDistanceBetweenMeshes( mesh1, mesh2 ) { //log("mesh1="+mesh1); //log("mesh2="+mesh2); var v1 = mesh1.position; var v2 = mesh2.position; var dx = v1.x - v2.x; var dy = v1.y - v2.y; var dz = v1.z - v2.z; var result = Math.sqrt( dx * dx + dy * dy + dz * dz ); return result.toFixed(5); } and the final entry for now ... it could be refactored to find the orbit distance of a planet based on the planet speed. function calculateOrbitalSpeed(starSize, planetSize, planetOrbit) { //the formula for obital speed is ... planet velocity = SQRT (gravity constant • mass of star / radius of orbit) //but since the planet mass is negligible we are just using the mass of the star var planetOrbitRadius = planetOrbit/2; //var gravityConstant = (starSize*planetSize)/Math.pow(planetOrbitRadius, 2); var gravityConstant = (starSize)/Math.pow(planetOrbitRadius, 2); planetSpeed = Math.sqrt(gravityConstant*starSize)/planetOrbitRadius; return planetSpeed; }
  3. Hello, I'm migrating my index.html phaser code to different javascript files for better structure and organisation; but I'm coming upon a problem. I've decided to use the template to make the game responsive "Basic Responsive Template" The templates features different states: boot, preload, game, and mainmenu as js files. I load all these in my HTML file and proceed to start from the "game" state. using a button I created in "Mainmenu". In the "create" method, of the "game" state, I call the createButtons function. This function is stored in another JS file that is loaded in the HTML file, before loading the phaser states. here is the createButtons code : function createButtons(){ //Mountain Brush buttonGroup = this.add.group(); buttonMountain = this.add.button(736, 32, 'buttons', mountainOnClick, this, "mountainbutton0.png","mountainbuttonpush.png", "mountainbuttonpush.png"); buttonMountain.fixedToCamera = true; buttonGroup.add(buttonMountain) function mountainOnClick () { currentLayer = terrainPop; currentTile = 5; } In the "game" state here is the code I use to call createButtons create: function () { //========================== WORLD CREATION //Make our game world and set it bounds this.world.setBounds(0, 0, gameWorldX*32, gameWorldY*32); // ========================== TERRAIN CREATION //create Blank tilemap terrainLayer = this.add.tilemap(); // add a tileset Image to the map terrainLayer.addTilesetImage(tileSetImage); //create the world as a layer terrain = terrainLayer.create('level1', gameWorldX, gameWorldY, 32, 32); terrainPop = terrainLayer.createBlankLayer('level2', gameWorldX,gameWorldY,32,32) terrainLimbo = terrainLayer.createBlankLayer('limbo', gameWorldX,gameWorldY,32,32) // Fills tilemap layer with default tile:HOLY WATER (6) terrainLayer.fill(0, 0,0,gameWorldX,gameWorldY, 'level1'); //allows camera to move around terrainLayer.fixedToCamera = false; currentLayer = terrain; createButtons(); },// End of Create When trying to load the state, I get the error: "TypeError : this.add is undefined" on the createButtons.js:3:1; I don't understand why createButtons isn't working in the scope of the create method I've been beating my head at this all day long and couldn't find any solution; i'm pretty sure it's a noobie mistake and would be grateful for some help! Thanks a lot
  4. I built a simple game using phaser, but didn't use multiple game states. The game had only one screen and no states! It was all poorly done. So now I'm learning game states. In this code snippet, taken from a phaser game https://github.com/alexdantas/ludum-dare-29/blob/master/js/states/play.js, we have, for example, a line consisting of this.game.camera.setBoundsToWorld(). I know how this works, but i'm having trouble knowing who is this here. I know this in OOP refers to the "owner" of the function, but in this case, who is it? Another doubt I'm struggling with is, where does the .game.camera.setBoundsToWorld() comes from? Is it from when Phaser initializes a new state? When it start a new state, does it create a new "main state", which in this case is what the "this" refers to, and add attributes/methods to it? Like this game.camera.setBoundsToWorld() method? function Play() {} Play.prototype = { create: function() { this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.stage.backgroundColor = '#000'; // initialize game variables this.cash = 0; this.chunkGroup = this.game.add.group(); this.nextChunkY = 0; this.game.world.bounds.x = 0; this.game.world.bounds.height = 1024; this.game.camera.setBoundsToWorld(); this.lastChunkIndex = 0; this.tephra = this.game.add.group(); this.rocks = this.game.add.group(); this.gems = this.game.add.group(); this.carrots = this.game.add.group(); this.lastChunk = null; this.chunkIndex = 0; this.generateChunk(); this.generateChunk(); }, }
  5. Hello, I'm currently learning phaser and have been going through the Zenva courses as well as tuts from phaser.io and other online sources and last night I had a main menu screen working just fine and decided to break up the code into more manageable files with a boot.js, preload.js, mainmenu.js, etc. and I'm stuck on an error where it will not move on to the main menu state due to an 'Uncaught ReferenceError: actionOnClick is not defined'. However, it is defined. When I had my file working, I had the function syntax as: function preload (){} function create () {{ function update () {} function actionOnClick (){} etc. However, in the lessons that have the code spread over multiple files, I see the syntax of the functions as: Game.MainMenu = function(){}; Game.MainMenu.prototype = { create: function () {}, (with a comma after each method)actionOnClick () {}etc. After formatting my code like the above comma-separated syntax, I am getting the Uncaught reference error. I have tried reordering the functions thinking maybe the actionOnClick needed to be above the create: function(), but that's not working. Can someone please explain the difference of the function syntax above and why commas are used to separate methods in the one syntax and not the other? Is there a reasoning to using one over the other? And how might I solve the reference error? Thank you very much in advance! Ryan
  6. I am building a game using this for the structure: https://github.com/photonstorm/phaser-examples/blob/master/examples/wip/state/test1.php Each state is a separate .js file. As a test I have taken an existing game I developed in a single file (which works fine) and broke it up into the states to test the pieces and parts. My problem is that I can get everything to work fine until I try to add a new function outside of these: BasicGame.Game.prototype = { create: function () { // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! }, update: function () { // Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out! }, quitGame: function (pointer) { // Here you should destroy anything you no longer need. // Stop music, delete sprites, purge caches, free resources, all that good stuff. // Then let's go back to the main menu. this.state.start('MainMenu'); }An example would be -- if I put the below into the update: function: this.physics.arcade.overlap(player, stars, collectStar, null, this);And add this new function: collectStar: function (player, star) { // Removes the star from the screenstar.kill();}The game does not work. If I comment the above out -- it works fine. I have tried everything and I am convinced I am probably missing something easy. Any assistance would be greatly appreciated.
  7. Hello! For my project I want to re-arrange an interesting feature: the rotation of the object by clicking in the right direction (and of its movement) on the principle of moving the spacecraft to point and rotation to the desired degree. How can I make such a function? Example attached.
  8. Hi everybody I'm trying to collect some functions you created so it will be centralised here and maybe one day put in a plugin, if enough documented and well structured with the benediction of RaananW (see: http://www.html5gamedevs.com/topic/13851-introducing-babylonjsx/) ..."a repository collecting all of those(static) functions and offering them as a "plugin" would be a great idea for BJX. But it should be organized and administrated correctly. It should offer an added value for the users. If someone wants to take this under his/her wings, I will be more than happy to open such a repository... ...Let's try to first collect a few of those, create playgrounds for them and document them. When there are enough, they will need to be structured in a single js file for people to use. Not just scattered in many files. It is very important (for me, at least) that there will be an added value for a plugin, and that it will have a cause. For example - mesh manipulation plugin, where you can do all kinds of nice things with mesh and mesh creations. When you are ready to do that send me a PM, I will add you to the github developers and you can start commiting changes to the repository"... So if you want to share the gold nugget you created with our dynamic and friendly community, please put it here so we can send it maybe soon to RaananW and his team to create a plugin valuable for all of us. I propose you this structure but if you find a better one please propose it it should include The name of "creator(s)" and the "modifier(s)" The version number the field of the function (mesh manipulation, text manipulation , animation, and so on) The level of difficulty (very subjective : for experts always easy, but for beginner sometimes very difficult!) An explanation about what it does exactly The description of the parameters used in it An example What should be improved
  9. When creating States I've seen both people using Objects and Functions. I've noticed that in the Phaser Coding Tips all the examples are using Functions. Is there any advantage in using Functions over Objects in this case? I understand that using Functions + prototype is good for when you are creating classes and then instances of those classes, but in this case there is only 1 of each State in a game.
  10. Do functions take parameters implicitly? I need to check for overlap and kill a sprite if overlap is true. So far, this is my code: update: function() { this.physics.arcade.collide(player,ground); this.physics.arcade.collide(letters,ground); this.physics.arcade.overlap(player, letters, this.collectLetter, null, this); this.physics.arcade.overlap(letters, ground, this.killLetter, null, this);My functions are: collectLetter: function(player,letter) { letter.kill(); //increase score }, killLetter: function(letter,ground) { letter.kill(); }But this doesn't seem to be working. The sprite is not being killed in killLetter, when it overlaps with the ground. Although it is being killed in collectLetter, i.e, when a player overlaps with it.
  11. Hello, I'm trying to get a button in my game to use other functions, and I haven't quite figured out how, other than brute forcing it. // Let's say I have everything preloaded and I'm in my game state filevar main = function(game) { var button1; var button2;};// and my prototype is something likemain.prototype = { create: function() { button1 = this.add.button(0, 0, 'button1', this.button1); button2 = this.add.button(100, 100, 'button2', this.button2); } button1: function() { // I might want to use otherfunc to do stuff while doing other stuff } button2: function() { // this is where I want to use button1's function and do other things } otherfunc: function() { // does more stuff }}Help is greatly appreciated.
  12. I'm porting a Flash/AIR project to Phaser, and everything is going pretty smoothly so far, but I hit a really odd performance issue which I'm hoping someone can explain to me. When using a forEach loop on a phaser Group (called desksGroup) which only has 9 items in it, I get ~40fps on mobile. But if I get rid of that forEach loop, and instead put the code into the built-in update() function of each of the 9 sprites within the group, FPS drops to ~4. Here is the game loop with a forEach going through a group of sprites (desksGroup): GameState.prototype.update = function() { // kill any pencils that hit a wall game.physics.arcade.overlap(layerMap, pencilsGroup, pencilHitWall); // TODO: subclass "Sprite" so that these update functions call themselves desksGroup.forEach(function(desk) { clientsGroup.forEach(function(theClient) { // get closest client if (!desk.currentTarget || desk.currentTarget && game.physics.arcade.distanceBetween(desk, theClient) < game.physics.arcade.distanceBetween(desk, desk.currentTarget)) desk.currentTarget = theClient; // other ideas for targeting: least health, most health, slowest, fastest }); if (desk.currentTarget && desk.currentTarget.health > 0 && game.physics.arcade.distanceBetween(desk, desk.currentTarget) < desk.range) { if (game.time.now > desk.nextFire) { desk.nextFire = game.time.now + desk.fireRate; var pencil = pencilsGroup.getFirstExists(false); pencil.reset(desk.x, desk.y); pencil.lifespan = desk.fireLife; pencil.rotation = game.physics.arcade.moveToObject(pencil, desk.currentTarget, desk.fireSpeed); } } }); game.physics.arcade.overlap(clientsGroup, pencilsGroup, pencilHitClient); if(defaults.showHealth) { clientsGroup.forEach(function(client) { game.debug.geom(new Phaser.Rectangle(client.x, client.y - 16, Math.max(0, tilemap.tileWidth * (client.health / defaults.health)), 7), '#00ff00', true); }); }}And here is a slightly modified version, with that forEach removed: GameState.prototype.update = function() { // kill any pencils that hit a wall game.physics.arcade.overlap(layerMap, pencilsGroup, pencilHitWall); game.physics.arcade.overlap(clientsGroup, pencilsGroup, pencilHitClient); if(defaults.showHealth) { clientsGroup.forEach(function(client) { game.debug.geom(new Phaser.Rectangle(client.x, client.y - 16, Math.max(0, tilemap.tileWidth * (client.health / defaults.health)), 7), '#00ff00', true); }); }}With the desk update functions moved to this: var deskUpdate = function() { var desk = this; clientsGroup.forEachAlive(function(theClient) { // get closest client if (!desk.currentTarget || desk.currentTarget && game.physics.arcade.distanceBetween(desk, theClient) < game.physics.arcade.distanceBetween(desk, desk.currentTarget)) desk.currentTarget = theClient; // other ideas for targeting: least health, most health, slowest, fastest }); if (desk.currentTarget && desk.currentTarget.health > 0 && game.physics.arcade.distanceBetween(desk, desk.currentTarget) < desk.range) { if (game.time.now > desk.nextFire) { desk.nextFire = game.time.now + desk.fireRate; var pencil = pencilsGroup.getFirstExists(false); pencil.reset(desk.x, desk.y); pencil.lifespan = desk.fireLife; pencil.rotation = game.physics.arcade.moveToObject(pencil, desk.currentTarget, desk.fireSpeed); } }}As you can see, the only difference is that I've removed the desksGroup.forEach() code block, and created an updateDesk function. Elsewhere in the code, where I instantiate the "desk" Sprites, I have the following line: desk.update = deskUpdate;I was thinking that by adding the deskUpdate function to each desk Sprite, it would save some overhead (since the .update() gets called automatically, instead of my explicitly looping through the group via forEach). However, when I use this deskUpdate function, my FPS on mobile drops from ~40fps to ~4fps. I also tried using an regular function declaration (function deskUpdate() {...}), and had the same performance loss.
  13. (Warning, new Phaser user ahead) I´m making my first tests with States on Phaser, and I am now having a problem creating functions inside states that are not the predefined ones (create, update, etc). All in all, this is the code that is giving me trouble: this.physics.arcade.overlap(player, stars, collectStar, null, this);I define my collectStar function like this, before it is ever called: collectStar: function(){// Removes the star from the screen star.kill(); // Add and update the score score += 10; scoreText.text = 'Score: ' + score;},This is inside a state on a different Javascript file called Lvl1.js. The error I am receiving when running on Chrome is this: Uncaught ReferenceError: collectStar is not defined Lvl1.js:127Line 127 is where collectStar is called.
  14. i using the dude complex mesh for an example.. but im trying to have him loaded as main player then be able to clone him with skeleton on keydown to test the clone ability. here is what i got.... // Dude BABYLON.SceneLoader.ImportMesh("him", "models/", "Dude.babylon", scene, function (newMeshes, particleSystems, skeletons) { newMeshes[0].position = new BABYLON.Vector3(0, 0, 5); // The original dude var dude = newMeshes[0]; dude.scaling = new BABYLON.Vector3(0.05,0.05,0.05); CREAT = dude; _CREAT = skeletons[0]; follow.target = CREAT; // target });window.addEventListener("keydown", function (evt) { switch (evt.keyCode) { case 83: createdude(); break; default: break; }var createdude = function () { dudes = []; var xrand = Math.floor(Math.random() * 501) - 250; var zrand = Math.floor(Math.random() * 501) - 250; var c2 = CREAT.clone(CREAT.name); c2.id = CREAT.name+(dudes.length+1); c2.position = new BABYLON.Vector3(xrand, 0, zrand); c2.skeleton = _CREAT.clone(); scene.beginAnimation(_CREAT, 0, 120, 1.0, true); };when i execute my code.. i get no errors in the console and nothing happens? what might i be doing wrong... my main character loads but thats it. ty for all the help.
  15. I created a group with the enemies on the screen. Now I would like to have each enemy hit points (some 2 others 3 others 4, etc ...). Then I thought that if there is way to make a kind of stretched groups phaser (and that he extended class could add a variable to the health points of each enemy ..?) Or do inthe Sprite class phaser .... I do not know how I should approach this. Any help or ideas? Thanks.
  16. Hi there, I know that this topic is half-covered: http://www.html5gamedevs.com/topic/7658-dealing-with-mouse-wheel/?hl=mousewheel#entry45755 But I'm not getting it to work, I tried every event of the mouse class, but the wheel is just not working, this is my code: on the onCrete method: myGame.input.mouse.mouseWheelCallback = function(event){ console.log("Scroll by callback! " + event); if (!(event.wheelDeltaY == undefined || event.wheelDeltaY> myGame.world.height || event.wheelDeltaY < (-myGame.world.height))) { myGame.camera.setPosition(0, myGame.camera.y - event.wheelDeltaY); }; };It does not even log.The idea is to make a candy crash scroll map.I tried it both on my laptop's trackpad and on a PC with real mouse wheel. Every help is much appreciated.
  17. Hi guys, Maybe a silly question, but I recently started using States in my game and now I am converting my functions to work with states. The functions without parameters work fine, but the ones with parameters don't. For example, when I call: this.createBullet(x, y); I get the error: Uncaught typeError: undefined is not a function. The function createBullet(x, y) does exist, it is created like this: createBullet: function(x, y) { // blablabla content of function } p.s. these functions are in my Game.js state Can anyone tell me what I'm doing wrong? It has to be a silly mistake but I don't know how to fix it Thanks, Kevin
  18. I'm currently having troubles with states in my game. I just started using it so I'm certain I'm making a dumb mistake, but if you could help I would really appreciate it. The problem I'm having is that when I hit the Space Button, it triggers the start function in stateMENU again and again. Shouldn't the stateMENU end and not respond/react anymore? If you need any more information, let me know. Here's My Code This is in LOAD.js: var stateLOAD = { preload: function(){ this.game.stage.backgroundColor = "#FF0921"; this.game.load.spritesheet('player','redThief.png',50,95); }, create: function(){ this.game.state.start('menu'); }}; This is in MENU.js: var stateMENU = { create: function(){ game.stage.backgroundColor = "#8A8A8A"; var spaceBttn = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); spaceBttn.onDown.add(this.start,this); }, start: function(){ console.log('start'); this.game.state.start('play'); }};This is in PLAY.js: var bgColor = "#678543";var statePLAY = { create: function(){ console.log('CREATE'); game.stage.backgroundColor = bgColor; var moveKeys = game.input.keyboard.createCursorKeys(); }};^ When you hit spacebar during the 'play' phase, it triggers the code in the start function in stateMENU and the console logs 'start' along with 'create'. This is in GAME.js: var game = new Phaser.Game(600,400,Phaser.AUTO,'gameDIV');game.state.add('load',stateLOAD);game.state.add('menu',stateMENU);game.state.add('play',statePLAY);game.state.start('load');
×
×
  • Create New...