Search the Community

Showing results for tags 'gravity'.

More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • HTML5 Game Coding
    • News
    • Game Showcase
    • Coding and Game Design
  • Frameworks
    • Phaser
    • Pixi.js
    • Babylon.js
    • Panda 2
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered

Found 54 results

  1. Hi, Can I somehow (with physics plugin Oimo.js) set different gravity for different meshes? For example I want to simulate environment in water and I want to have there buoyancy. Thanks a lot for your advice.
  2. Demo sourecode

    Hello evryone, i try to better understand collisions & mehs interactions. I found this demo on the babylon.js 101 docs:,_mesh_collisions_and_gravity Is it possible to get the source code ?
  3. Hello! In Phaser ( particularly Phaser CE ) I can't find something like Wind Resistance for objects. And start thinking how to implement my own version: create(){ game.physics.startSystem(Phaser.Physics.P2JS); game.physics.p2.gravity.y = 100; = game.add.sprite(32, 32, "car"); game.physics.p2.enable(,false); = 0.4; } update(){ if( && > ){; } } With this I can't use big numbers for windResistance, only between 0 and 1. What do you guys think??
  4. Schubi Action and skill game in spirit of Thrust and Space Taxi. Play it at itch io: Hompage: PREFACE If puzzled by the first level please read "WHAT TO DO IN LEVEL 1" below. May take 30 seconds to 10 minutes to pickup and develop necessary skills. Difficulty level is nasty but easier than in the aforementioned classics. To solve all levels probably takes a week. If you happen to solve level 28, notify (the only level I failed at). MISSION Pilot your little yellow ship and load all trucks with cargo at a construction site (level) within the shift duration of 180 seconds. Cargo is picked up by flying over a dispenser (the circular object). This hooks cargo to the ship and a truck is loaded by ejecting the hooked cargo and hitting the truck with it. - 30 largely varying levels, playable in any order. - game within game principle, e.g. level 30 is a racing game. You may find some references to e.g. Asteroids, Thrust, Space Taxi and Cut The Rope in other levels. ON THE IMPLEMENTATION Wrote this as my first game in 2012. This html5 version is a mixture of transpiled javascript (emscripten) and normal javascript. No engines were used, everything was written from scratch (physics, collision detection,...). CONTROLS Keyboard only: A - turn ship left S - turn ship right K - thrust L - eject hooked cargo (keys above can be redefined in KEYS submenu) Quit a level / back in menu: B, Backspace or ESC Menu navigation and selection: Arrow keys and Return WHAT TO DO IN LEVEL 1 AND HOW TO DEVELOP THE NECESSARY BASIC SKILLS Your ship cannot cross the red white striped barrier, only cargo can. First fly around using keys A,S,K. If you got that fly over the dispenser (the green circular object). Now that the cargo is hooked to the ship fly some circles, halfcircles and watch the cargo gyrating around the ship. If you got that eject the cargo with L. Study its flying path. Pick up more cargo and practice throwing (hurling) the cargo so it reaches the trucks beyond the barrier. If you loaded all trucks, congratulations, you developed necessary skills for this game. One further useful skill to be developed is rotating the cargo to the ships nose (and keeping it there by maneuvering) so you can push it. Described in the game but overlooked: The yellow black striped areas are explosive ones. Do not touch them, neither with the ship nor drop cargo there. BROWSER REQUIREMENTS WebGL capable browser, may not work with MS Edge. There is no loading bar for the initial preloading of music. Be patient. There is also an Android version available from in a free to play bundle (see for links).
  5. Hello, I'm currently building a scene where a person walks through a room. There are several objects in the room. When I run and run against a large mesh, I collide and can't get through (it's wanted). When I walk towards a low (low height) mesh, I'm suddenly reset, probably to the old position. Camera position: [0.1.2, -2.25] Camera ellipsoid: [0.5,0.59,0.5] Scene gravity: [0, -9.81, 0] Bottom is at y = 0 How do I set the camera's collisionsbox correctly to run on the floor and not get the effect of low meshes? Thank you.
  6. I see the docs of the Body class But i am not sure which would be the right property to change. I have two balloons falling down and they might both at the same time or one after the other, hit my rectangle. The problem is, both objects stop moving after they hit the rectangle. i am sure this has to do something with physics. As if the vertical(y coordinate) velocity gets set to 0 when they hit the rectangle. Here is a sample code: graphics = si.gameObject.add.sprite(boxX, boxY, si.ImageAssetKeys.BALLOON_ANIM_ATLAS, 0); floatingAnim = graphics.animations.add('floating', si.GraphicsUtility.getFloatingAnimArray(), 30, true); splashAnim = graphics.animations.add('splash', si.GraphicsUtility.getSplashAnimArray(), 30, false); splashAnim.onComplete.add(si.LetterBox.splashComplete, this);'floating'); = graphics;, 0.5); = false; = false; = false; = true; = velocity; = false; = false; Which body property should I change to prevent the stop in movement of balloons?
  7. Hi there, my first post! I'm learning how to use Phaser by following a cool tutorial by Wild . At a moment he explains us how to move our player by using keyboard input. And everything works fine but the jump mouvement =/ And I don't understand why! (my browser console says nothing). Nothing happens when I press the up button. Here is my code if someone is willing to explain me a bit what's wrong? in the create player.animations.add('idle',[0,1],1,true); player.animations.add('jump',[2],1,true); player.animations.add('run',[3,4,5,6,7,8],7,true); this.physics.arcade.enable(player);; player.body.collideWorldBounds = true; controls = { right: this.input.keyboard.addKey(Phaser.Keyboard.RIGHT), left: this.input.keyboard.addKey(Phaser.Keyboard.LEFT), up: this.input.keyboard.addKey(Phaser.Keyboard.UP), }; And in the update function: this.physics.arcade.collide(player,layer); player.body.velocity.x=0; if (controls.right.isDown){'run'); player.scale.setTo(1,1); player.body.velocity.x += playerSpeed; } if (controls.left.isDown){'run'); player.scale.setTo(-1,1); player.body.velocity.x -= playerSpeed; } if (controls.up.isDown && (player.body.onFloor() || player.body.touching.down) && > jumpTimer){ player.body.velocity.y = -600; jumpTimer = + 750;'jump'); } if (player.body.velocity.x==0 && player.body.velocity.y==0){'idle'); } } I don't know if any other information would be useful?
  8. I thought this would be a simple fix, but so far can't figure it out at all. I have something I call trapledges that is going to fall in the y direction when colliding with player. However, I can not get them to stop moving in the x direction if the player touch the side of them. In my code I have a commented out if test in the update function. I've tried it out both there and in the else if test where the trapledges get made. also tried out different things in the test as changing velocity.x = 0; to for example gravity = 0; or trapLedge.immovable.x = true; and so on. Still won't stop floating to the side if the player touch the sides of the ledge, instead of landing ontop of it. Added two jpgs of the game, with an arrow showing how the ledge move. A cross to show which way I want the ledge to stop move. var playState = { create: function() { for (i = 0; i < 100; i++) { var trapRandomizer = (Math.random() * 0.6) + 0.3; var randomYPos = (Math.random() * 200) + 290; var randomXSize = (Math.random() * 0.6) + 0.3; var randomYSize =(Math.random() * 0.8) + 0.6; //console.log("x: " + randomXSize + "Ran" + trapRandomizer) if (trapRandomizer > 0.4) { var ledge = platforms.create(ledgeXPos, randomYPos, "ground"); ledge.scale.setTo(randomXSize, randomYSize); ledge.body.immovable = true; } else if (trapRandomizer <= 0.4) { console.log("Trapledge"); var trapLedge = trapPlatforms.create(ledgeXPos, randomYPos, "ground"); trapLedge.scale.setTo(randomXSize, randomYSize); trapLedge.body.immovable = false; } } update: function() { /* if (game.physics.arcade.collide(trapPlatforms, player)) { trapPlatforms.body.velocity.x = 0; trapPlatforms.body.velocity.y = 300; }*/ },
  9. Hi, I imported a mesh and then separated it into two objects. Basically a wheel and a stand for the wheel. And I want the axle for the wheel to fall onto the stand and allow me to spin the wheel. My problem is that I can't get the physics to work right. I either drop things through the floor or gravity doesn't work at all, depending on the different engines and things I've tried. I'm new to babylonjs so perhaps I'm doing wrong something that's simple to see. My code is at If anyone can see what I'm doing wrong, I'd much appreciate it!
  10. How to not apply gravity to weapon?

    Hi there, I'm creating a simple platform game where you can shoot enemies. I've applied game.physics.arcade.gravity.y = 1000; But this seems to now affect my weapon class and bullets too! How do I set my weapons or bullets to NOT be affected by gravity? Here's the code I've used for reference: var playState = { //code to make assets goes here create: function(){ /*-- creating player --*/ game.add.sprite(0, 0, 'background'); game.physics.arcade.gravity.y = 1000; //Do not enable, need to fix gravity. this.player = game.add.sprite(game.width/2, 780, 'player'); this.player.anchor.setTo(0.5, 0.5); game.physics.arcade.enable(this.player); this.player.body.gravity.y = 1500; this.player.body.bounce.set(0.3); this.player.body.collideWorldBounds = true; this.player.cursor = game.input.keyboard.createCursorKeys(); this.player.fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); this.player.hp = 100; this.player.weapon = game.add.weapon(30, 'bullet'); // this.player.weapon.enableBody = true; this.player.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.player.weapon.bullets.setAll('body.gravity.y', 0); this.player.weapon.bulletSpeed = 850; this.player.weapon.fireRate = 200; this.player.weapon.trackSprite(this.player);
  11. Hi @all again, is there a way to change the gravity for certain space? Case 01: I want for example that the player or other objects can fly to space. So if specific distance has been reached from the ground, the gravity should decrease with rising distance, until null. Case 02: If the player or other objects goes into a hidden area/space/box, the gravity for all objects in there is different to the world gravity (scene.gravity). Thanks for ideas.
  12. New noob

    Hello Happy New Year everyone I'm a french student which has a homework to make with phaser. I have then started to work and learn to use it and finally tried to make little game thanks the help of the many tutorials and examples on the web but i'm quite bad and i'm finally stuck at this point. For now the problem is to create many little alien (it will be change later) at the right of the screen and make them go to the left in a repetitive way but i tried one thousand method and always failed as you can see my last attempt XD if someone know how to do pls help (sry for the english). the actual code : <script type="text/javascript" src="js/phaser.js"></script> <script type="text/javascript"> var game = new Phaser.Game(1000, 400, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { game.load.image('alien', 'assets/alien.png'); game.load.image('background', 'assets/background.png'); game.load.image('bullet', 'assets/bullet.png'); game.load.spritesheet('vaisseau', 'assets/vaisseau.png', 32, 48); } var sprites; var vaisseau; var alien; var background; var cursors; var bullets; var bulletTime = 0; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); background = game.add.tileSprite(0, 0, 1000, 400, 'background'); bullets =; bullets.enableBody = true; bullets.physicsBodyType = Phaser.Physics.ARCADE; bullets.createMultiple(30, 'bullet'); bullets.setAll('anchor.x', 0.5); bullets.setAll('anchor.y', 0.75); bullets.setAll('outOfBoundsKill', true); bullets.setAll('checkWorldBounds', true); vaisseau = game.add.sprite(100, 200, 'vaisseau'); vaisseau.anchor.setTo(0.5, 0.5); game.physics.enable(vaisseau, Phaser.Physics.ARCADE); vaisseau.body.collideWorldBounds = true; cursors = game.input.keyboard.createCursorKeys(); fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); sprites =;, createSprite, this); } function createSprite() { var alien = sprites.create(1000,, 'alien'); } function fireBullet () { if ( > bulletTime){ bullet = bullets.getFirstExists(false); if (bullet){ bullet.reset(vaisseau.x, vaisseau.y + 8); bullet.body.velocity.x = 400; bulletTime = + 400; } } } function update() { background.tilePosition.x -= 2; if (vaisseau.alive){ vaisseau.body.velocity.setTo(0, 0); if (cursors.down.isDown){ vaisseau.body.velocity.y = 200; }else if (cursors.up.isDown){ vaisseau.body.velocity.y = -200; }else if (cursors.left.isDown){ vaisseau.body.velocity.x = -200; }else if (cursors.right.isDown){ vaisseau.body.velocity.x = 200; }if (fireButton.isDown){ fireBullet(); } } sprites.x -= 5; } </script>
  13. Gravity

    Hi. I'm trying to make my first game with Phaser and I'm trying to get some physics working - global gravity. I'm not sure whats going on but somethings not working: = { create : function() { this.background =, 0,, 360, 'background'); this.background.autoScroll(-100, 0); this.background =, 290,, 8, 'ground'); this.background.autoScroll(-180, 0); this.player = this.add.sprite(30, 230, 'player'); this.player.animations.add('run');'run', 10, true); // physics engine; // gravity = 400; }, based on a couple tutorials I've been following I was expecting for the 'ground' to fall, but it does not. I'm still really new to Phaser and kinda new to JS, so i figure I'm overlooking something simple. I actually only need gravity on the player sprite so if you could suggest how to go about that I would appreciate in but would be happy just to get some gravity of any kind to start with. Thank you in advance for your help.
  14. Gravity Melee

    Hello Everybody!! I present to you, the BEST multiplayer casual space shooter game on the Internet today! -->WHAT IS IT ABOUT?? 1. It is a 2 dimensions multiplayer space game that is gravity based. 2. Your spaceship has stats that you can improve by either collecting items in space or by destroying other player's ship. 3. Everything in the game has mass, and newtonian physics has influence over everything. Entities are attracted to each other according to roughly (mass1*mass2)/distance^2. 4. Your ship has two basic stats that determine its defense, its armor amount and shield amount 5. Shield recharges according to the amount of shield you have left, you can add to your total shield amount by acquiring the right item floating in space. 6. Armor do not recharge, every unit of armor you add to your ship add a certain amount of mass to your ship. Your ranking is determined by your total MASS! 7. You can repair your armor if you have enough unit of "armor repairer". Can be found floating in space. 8. The force of your propulsion system can be modified by item you find in space. The bigger you get, the more propulsion power you need to accelerate. 9. The rate of fire (RoF) can also be increased by item found in space, as well as the damage that each of your projectile !! //---------------------------------------------------------------------------------------- UPDATES ----------------------------------------------------------------------------------------------// 1. 28/11/2016 ---> Addition of the Flash Bomb, uses shield and deals damage to surrounding area according to how much shield you had when you fired it. //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// VISIT AT !!!----> Feel free to ask any question!!!!!!!! <----!!! --> IS THIS GAME HTML5?? - yes, the front end is mostly an html5 canvas and javascript, the back-end is node.js.
  15. Free Camera falling

    Hello, When I am using free camera and attached controls, camera is falling only for about 1 second and than stops. I have to press control key to begin falling again. Can increase this duration or give camera instruction to fall (something like moveWithCollisions )? Thanks!
  16. Sticky collisions in Arcade physics

    I am building a basketball game. I cannot get the ball to stop sticking to the rim colliders. When I was running p2 physics, the ball would simply bounce off the rim colliders as expected, but now, everytime the ball touches the rim colliders, it slows down movement rapidly and doesn't bounce or fall as expected. I think I might be missing a property setting somewhere. I set the rim colliders (leftMarker + rightMarker) to be immovable in create() but I'm not sure what else I need. I don't understand why the colliders stick to each other! Any help is appreciated! Basketball.Game = function (game) { this.score = null; this.scoreText = null; this.ball = null; = null; this.basket = null; this.rim = null; this.leftMarker = null; this.rightMarker = null; this.checker = null; this.ballCollisionGroup = null; this.rimCollisionGroup = null; this.collisionsOn = false; this.launched = false; this.respawned = false; this.lastPointerPos = null; //HTML element that will produce screenshot this.clickToSave = null; //Constants this.GRAVITY = 1600; this.SHOOT_FORCE = 1400; this.EDGE_CUSHION = 10; this.SCALE_PERCENT = 0.55; }; Basketball.Game.prototype = { create: function () { //Initialize physics world; = this.GRAVITY; //Create basket group this.basket =; //Load net sprite =, - 200, 'net');; this.basket.add(; //Load hoop markers this.leftMarker = - 57, 232, 'marker'); this.rightMarker = + 57, 232, 'marker'); this.leftMarker.anchor.setTo(0.5); this.rightMarker.anchor.setTo(0.5); this.basket.add(this.leftMarker); this.basket.add(this.rightMarker); //Load ball sprite this.ball =, - 100, 'ball'); this.ball.anchor.setTo(0.5); //Load rim sprite this.rim =, - 200, 'rim'); this.rim.anchor.setTo(0.5); this.basket.add(this.rim); //Load checker sprite this.checker =, - 80, 'checker'); this.checker.anchor.setTo(0.5); this.basket.add(this.checker); //Setup physics[this.leftMarker, this.rightMarker, this.ball]); this.leftMarker.body.setCircle(this.leftMarker.width / 2); this.rightMarker.body.setCircle(this.rightMarker.width / 2); this.leftMarker.body.moves = false; this.rightMarker.body.moves = false; this.leftMarker.body.immovable = false; this.rightMarker.body.immovable = false; this.leftMarker.body.enable = false; this.rightMarker.body.enable = false; this.ball.body.setCircle((this.ball.width * this.SCALE_PERCENT) / 2); this.ball.body.allowGravity = false; this.ball.body.bounce.set(0.8); this.ball.body.velocity.set(0); //Enable input, this);, this); //Initialize this.score = 0; this.scoreText =,, 'pixel', 'Score: ' + this.score, 36); this.scoreText.anchor.setTo(0.5); this.lastPointerPos = new Phaser.Point(0, 0); //For mobile Phaser.Canvas.setTouchAction(, 'auto'); = true; }, update : function () {, this.leftMarker);, this.rightMarker); //Only enable collisions when the ball is above the net markers if (this.ball.y < this.basket.children[1].y - this.ball.height / 2) { console.log("Detect collisions!"); this.leftMarker.body.enable = true; this.rightMarker.body.enable = true; } //Check if the ball is out of bounds if (this.ball.x < - this.ball.width / 2 || this.ball.x > + this.ball.width / 2|| this.ball.y < - this.ball.height / 2 || this.ball.y > + this.ball.height / 2) { //Respawn the ball if it hasn't already if (!this.respawned) { this.respawn(); } } }, render : function () {; if (this.leftMarker.body.enable) {;; } }, track : function () { //Update the last finger position this.lastPointerPos.x = this.input.x; this.lastPointerPos.y = this.input.y; //Set the ball physics to be still this.ball.body.allowGravity = false; this.ball.body.velocity.set(0); this.launched = true; }, launch : function () { //Launch the ball if it hasn't already if (this.launched) {{ x: this.SCALE_PERCENT, y: this.SCALE_PERCENT }, 1000, Phaser.Easing.Linear.Out, true); this.launched = false; this.ball.body.allowGravity = true; //Get the direction of finger swipe, normalize it, and apply a scalar to the velocity of the ball var direction = new Phaser.Point(this.input.x - this.lastPointerPos.x, this.input.y - this.lastPointerPos.y); Phaser.Point.normalize(direction, direction); if (direction.y < 0) { this.ball.body.velocity.x = direction.x * this.SHOOT_FORCE; this.ball.body.velocity.y = direction.y * this.SHOOT_FORCE; } } }, respawn : function () { this.respawned = true; //Set the ball physics to be still again this.ball.body.allowGravity = false; this.ball.body.velocity.set(0); //Disable collisions this.leftMarker.body.enable = false; this.rightMarker.body.enable = false; * 0.25, function () { this.respawned = false; //Rescale the ball and its body this.ball.scale.setTo(1); this.ballResized = false; //Spawn the ball in a new, random location var ballSpawnX = + this.ball.width / 2 + this.EDGE_CUSHION, ( - this.ball.width / 2) - this.EDGE_CUSHION); ballSpawnX =, 10); //Make sure the ball is in the boundary we set if (ballSpawnX < this.ball.width + this.EDGE_CUSHION) { ballSpawnX = this.ball.width + this.EDGE_CUSHION; } else if (ballSpawnX > - this.EDGE_CUSHION) { ballSpawnX = - this.EDGE_CUSHION; } this.ball.x = ballSpawnX; this.ball.y = - 100; }, this); }, saveCanvas : function () { var link ='image/png');, '_blank'); } };
  17. Hello I got a 3dModel of an elevator. I trigger a button for it's position with the following code: myMesh.actionManager.registerAction(new BABYLON.InterpolateValueAction(BABYLON.ActionManager.OnPickTrigger, myMesh,"position.y",-2.6, 1000)) //down .then(new BABYLON.InterpolateValueAction(BABYLON.ActionManager.OnPickTrigger, myMesh,"position.y",0.001, 1000)); //up Witch works great! Accept when my char wants to get up again, he is falling through the ground, - the mesh. Few workarounds that come into my head, like check the state of the "event" an apply new gravity or new cam position. What's the easiest one? Any suggestions are highly appreciated! Best
  18. I'm working on a game with a tilemap and arcade physics. The gravity is set to 1000 for the player and enemies movements and interacting which all work fine. However, when I add a particle emitter the particles also fall down? I've tried setting emitter.gravity to "0" but that doesn't help. The only thing that stops the particles from falling is disabling the line that sets game.physics.arcade.gravity.y, which is not what I want because the gravity is needed for the game. So my question is: how to disable the gravity of emitter particles? I've created a fiddle with example code here: Btw this is similar to this old thread which doesn't have a clear answer, as far as I can tell. function create() { // set stage physics game.stage.backgroundColor = 0x808080; game.physics.startSystem(Phaser.Physics.ARCADE); game.physics.arcade.gravity.y = 1000; // add particle emmiter emitter = game.add.emitter(0, 0, 200); // x=0, y=0, maxParticles=200 emitter.makeParticles('particles', [0, 1, 2, 3]); //emitter.setXSpeed(-120, +120); //emitter.setYSpeed(-120, +120); emitter.setXSpeed(0, 0); // testing; particles should not move at all emitter.setYSpeed(0, 0); emitter.setRotation(0, 0); emitter.gravity = 0; // no gravity on particles // test sparkles will still fall down emitter.x = CANVAS_WIDTH / 2; emitter.y = CANVAS_HEIGHT / 2; emitter.start(true, 2000, null, 10); // explode=true, lifespan=800, freq=null, quantity=10 } function render() { var testparticle = emitter.getFirstExists(); if (testparticle) game.debug.bodyInfo(testparticle, 10, 10); }
  19. Group Pivot Point with P2 Gravity

    Hi all, very new to Phaser and I'm trying to basically make a colour switch kind of game. So I am using p2 physics for the rotating arcs so I can add collision detection later. I had these arcs as graphics in the game but then couldn't add physics to them so they are now sprites in a group call wheel. I have the pivot point of the group set to (85,85). I don't know why but this number works, the sprites are 170x170 but when I try to give the group a pivot point such as (0.5,0.5) it doesn't work I've even tried (0.25,0.25) to try and recreate the (85,85) pivot point. I am trying to do this because when I apply the p2 gravity to the game the wheels pivot point does not move so the wheels rotation gets bigger and bigger. If anyone has a possible solution to this or an alternative method to go about this then please reply! I'm so desperate right now it's not even funny.
  20. [WIP] Planet Boom

    i would like to show you guys my first browser game, Planet boom, it's in an incomplete state since i was working on it for a workshop, but of course you can check out the code (which is kinda crappy) and if you like the concept you can probably contribute to the project, i'm always willing to join teams or collaborate on projects.
  21. Drag drop game

    Right, I'm new. Hello! This might help someone. It's an example of drag and drop, collision detection and physics (a drag puzzle game). I sketched it pretty quickly, and I'm sorry it's not commented. Bit messy but you should be able to grab the helpful bits. I had a nightmare putting this together to be honest, but on the 5th evening this is the result, so I'm pleased. I'll update it soon to make things clearer. SHARE YOURS! <html xmlns=""><head> <script src="hand.js"></script> <script type="text/javascript" src="cannon.js"></script> <script src="babylon.js"></script> <script src="jquery.min.js"></script> <script type="text/javascript" src="oimo.js"></script> <style> html, body { width: 100%; height: 100%; margin: 0; padding: 0; } #renderCanvas { width: 100%; height: 100%; touch-action: none; } .debugDiv{ display:nones; } </style> </head> <body> <div class="debugDiv"></div> <canvas id="renderCanvas"></canvas> <script> var boxes = new Array(); var materials = new Array(); var box1, box2, blueBox, camera, scene, ground; var canvas = document.querySelector("#renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var mazeSize = 3; var createScene = function(){ scene = new BABYLON.Scene(engine); var canvas = engine.getRenderingCanvas(); var startingPoint; var currentMesh; var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 0, new BABYLON.Vector3(0, 5, 0), scene); camera.setPosition(new BABYLON.Vector3(200,150, 10)); scene.clearColor = new BABYLON.Color3(0, 0, 0); camera.attachControl(canvas, true); scene.enablePhysics(new BABYLON.Vector3(0, -500, 0), new BABYLON.OimoJSPlugin()); ground = BABYLON.Mesh.CreateGround("ground", 1000, 1000, 1, scene, false); ground.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {mass:0, friction:0.5, restitution: 1}); ground.visibility = 0; createWalls(); createBoxes(); var getGroundPosition = function(){ var pickinfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh){return mesh == ground;}); if(pickinfo.hit){return pickinfo.pickedPoint;} return null; } var onPointerDown = function (evt) { if (evt.button !== 0){return;} var pickInfo = scene.pick(scene.pointerX, scene.pointerY, function(mesh){ return mesh !== ground;}); if(pickInfo.hit){ currentMesh = pickInfo.pickedMesh; startingPoint = getGroundPosition(evt); if(startingPoint){setTimeout(function(){camera.detachControl(canvas);}, 0);} } } var onPointerUp = function(){if(startingPoint){camera.attachControl(canvas, true); startingPoint = null; return;}} var onPointerMove = function(evt){ if(!startingPoint){return;} var current = getGroundPosition(evt); if(!current){return;} var diff = current.subtract(startingPoint); if(currentMesh.draggable){return;} currentMesh.moveWithCollisions(diff); startingPoint = current; currentMesh.updatePhysicsBodyPosition(); } $(canvas).bind("pointerdown", onPointerDown).bind("pointerup", onPointerUp).bind("pointermove", onPointerMove); scene.onDispose = function(){$(canvas).unbind("pointerdown", onPointerDown).bind("pointerup", onPointerUp).bind("pointermove", onPointerMove);} return scene; }; function createBoxes(){ matUnit = (1/mazeSize); blocks = new Array(); for(x=0;x<mazeSize;x++){ for(y=0;y<3;y++){ //materials materialsIndex = materials.length; materials[materialsIndex] = new BABYLON.StandardMaterial("texture1", scene); var m = materials[materialsIndex]; = materialsIndex; m.diffuseTexture = new BABYLON.Texture("profilePic.jpg", scene); m.diffuseTexture.uScale = 1/mazeSize; m.diffuseTexture.vScale = 1/mazeSize; m.diffuseTexture.uOffset = matUnit*(-(x+1)); m.diffuseTexture.vOffset = matUnit*(0+y); boxIndex = boxes.length; boxes.push(BABYLON.Mesh.CreateBox("red", 49.9, scene)); var b = boxes[boxIndex]; = materialsIndex; b.position.y = 25.1; b.position.x = 50-(50*y); b.position.z = 50-(50*x); b.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {mass:0.1, friction:0.1, restitution:0.1}); b.checkCollisions = true; b.ellipsoid = new BABYLON.Vector3(24, 24, 24); coords = [Math.round(b.position.x),Math.round(b.position.z)]; m.coords = coords; b.coords = coords; if(x == mazeSize-1 && y == mazeSize-2){ coords = [Math.round(b.position.x),Math.round(b.position.z)]; m.coords = coords; b.coords = coords; break; } } } swapArrayElements(boxes, 5, 7); swapArrayElements(boxes, 4, 7); //swapArrayElements(boxes, 3, 7); //shuffle(boxes); for(x=0;x<materials.length;x++){boxes[x].material = materials[x];} } function createWalls(){ wallScaleAxis = new Array("x","z","x","z"); wallDimsArr = new Array([25*mazeSize, 25, 0],[0,25,25*mazeSize],[0-(25*mazeSize),25,0],[0,25,0-(25*mazeSize)]); wallsArr = new Array(); lightsArr = new Array(); for(x=0;x<4;x++){ lightsArr[x] = new BABYLON.PointLight("omni", new BABYLON.Vector3(wallDimsArr[x][0]*2, 150, wallDimsArr[x][2]*2), scene); lightsArr[x].intensity = 0.3; wallsArr[x] = BABYLON.Mesh.CreateBox("ground", 50*mazeSize, scene); var w = wallsArr[x]; w.scaling[wallScaleAxis[x]] = 0.001; w.scaling.y = 0.5; w.position = new BABYLON.Vector3(wallDimsArr[x][0], wallDimsArr[x][1], wallDimsArr[x][2]); w.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {mass:0}); w.checkCollisions = true; w.draggable = true; w.ellipsoid = new BABYLON.Vector3(25*mazeSize, 25, 0.01); w.showBoundingBox = false; w.visibility = 0; } } var scene = createScene(); engine.runRenderLoop(function(){scene.render();}); $(window).bind("resize", function(){engine.resize();}); function swapArrayElements(arr, indexA, indexB){ var temp = arr[indexA]; arr[indexA] = arr[indexB]; arr[indexB] = temp; return arr; }; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } doer = 0; function showBoxPos(){ doer++; $(".debugDiv").html(doer) correct = 1; for(x=0;x<boxes.length;x++){ boxes[x].coords = [Math.round(boxes[x].position.x),Math.round(boxes[x].position.z)]; if(!(boxes[x].coords.toString() == materials[x].coords.toString())){correct++; break;}; } for(x=0;x<4;x++){ if(correct <= 1){ for(y=0;y<boxes.length;y++){ boxes[y].setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {mass:-10}); boxes[y].updatePhysicsBodyPosition(); boxes[y].draggable = true; } clearTimeout(boxTimer); ground.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {mass:1, friction:0.5, restitution: 1}); break; } } } var boxTimer = setInterval(showBoxPos, 1) </script> </body> </html>
  22. How can I get my mesh moving around on a height field when using Oimo Plugin in Babylon js? This is "working": Render.prototype.createScene = function(){ this.ground = BABYLON.Mesh.CreateGroundFromHeightMap("ground", "textures/heightMap.png", 50, 50, 100, 0, 2, this.scene, false, onGroundCreated);}function onGroundCreated(ground){ ground.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, {friction:0, mass: 0, move : false });}The problem is, as the Imposter is a Box, my Mesh moves just on top of the height field. In this tutorial: It states four different possibilitys for colliders. Box, Sphere, Capsule and Mesh. Is Capsule and Mesh also available in the Babylon OimoJSPlugin? Because I guess thats what I would need to move around the height field i guess. Or maybe there are other valid options for that problem.
  23. Specify gravity centre

    I've looked through the examples but can't find the answer to my query. I've an idea for a game that would require me to have a specified centre of gravity rather just gravity applied to the game world dragging objects to the bottom. Is this supported in any of the physics engines? eg a spaceship flying past a planet would be affected by it's gravity
  24. Inverse gravity, walk on ceiling

    Hey guys, I was wondering if something like this: can be done with Phaser. Does anyone have any example of this functionality, or ideas how should I implement this? I'm thinking rotating the character and then applying negative gravity, with a ceiling collision to prevent it from "falling" upwards. What do you think?
  25. Hi I have applied a freecamera to my project. camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(-40, cameraHeight,-132), scene); I have applied gravity to it so that it won't fly ie: camera.applyGravity = true; I have given it a constant height (cameraHeight) scene.registerBeforeRender(function () { scene.activeCamera.position.y = cameraHeight; }); Now the problem is that when I move the mouse up and down along the Y axis the camera rotates (in essence on the x-axis). So the camera is elevated and it's like flying.I have checked the ESPILIT demo and it's the same problem (Espilit.babylon has camera gravity enabled). So is there a command which limits the rotation of the free camera up and down (or left and right) ? If I need to calculate the rotation in registerBeforeRender then my 2nd question, can I stop a camera?