Search the Community

Showing results for tags 'collision detection'.

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.js
    • melonJS
    • Haxe JS
    • Kiwi.js
  • General
    • General Talk
  • Business
    • Collaborations (un-paid)
    • Jobs (Hiring and Freelance)
    • Services Offered

Found 30 results

  1. Hi all, I'm working on a little racing game and using this map: I'm using p2 physics. Whenever the car touches the gras it should become slower. In order to achieve that I cut out the inner gras and created a polygon shape for it. /*Adding car*/ car = game.add.sprite(1100,300,'car');"car"; car.width=100; car.height=175; game.physics.p2.enable(car); car.body.angle = 90;; inner_gras = game.add.sprite(1320, 940, 'gras'); game.physics.p2.enable(inner_gras); inner_gras.body.kinematic = true; inner_gras.body.clearShapes(); inner_gras.body.loadPolygon('collision', 'inner_gras');"inner_gras"; For the collision detection I use game.physics.p2.setPostBroadphaseCallback(): game.physics.p2.setPostBroadphaseCallback(hitGras, this); function hitGras(body1,body2){ if(( === "inner_gras" && === "car") ||( === "car" && === "inner_gras")){ console.log(body1);//console.log(body2.sprite); return true; } else{ return false; } } The collision detection works fine, but whenever I try to do something else than returning true, for example changing the speed or something else, a contact between the car and the inner_gras sprite is detected, where they shouldn't have any contact. It seems like the inner_gras sprite does still have the rectangular shape, although applying clearShapes(). Any ideas or suggestions on how to solve this problem, or what to use instead? Thanks in advance!
  2. hi all, When ever we make collision check it will take the width and height of the image or object which we are giving . Now can we change width and height of the collision check alone .in my case my image size is 100*100 but while dragging and droping i am making collision check in which it taking 100*100 for check but i wana change it to 200*200 can it be possible . i tried changing the image with and height while dragstart,dragmove and pointerdown ,but still for collision it will take 100*100 only
  3. Hi, I'm running into an issue regarding collision detection against adjacent DisplayObjects. Let's say I have sibling objects that are a child of a Container that has been rotated. If I use getBounds() on the siblings they return a bounding box that is oriented to cardinal north. Using those bounds for collision detection may result in false positives, because the given bounds may not follow the actual shape and orientation of the DisplayObject. I created a codepen to illustrate the point: When you toggle the "rotate" buttons at the bottom of the pen you will see the purple box morphing to the shape of the bounds for "shape" and "label". The text will change from red to green if the collision detection returns positive. I would like to do a more robust collision detection algorithm (possibly based on Separating Axis Theorem), but I would need to grab the vertices for each shape correctly translated to the global coordinates regardless of their nesting within the scene graph (accounting for scale, rotation, and translation from the shape and all parent transforms). The case being that the collision detection that I would like to do may not be only between direct siblings within the scene graph. Is there a nested property that would give me what I'm looking for, or will I need to grab the graphics data and apply all of the recursive parent transforms myself for each vertex? Here is a fork of a codepen that demonstrates the Separating Axis Theorem:
  4. Hey! I have a group of enemies created like this (called from create()): spawnEnemies: function(map){ this.enemies =; this.enemies.enableBody = true;; var enemyStartPositions = this.findObjectsByType('enemyStart',, 'objectLayer'); for(var i = 0; i < enemyStartPositions.length; i++){ var enemyStart = enemyStartPositions[i]; var enemy = new Enemy(, enemyStart.x, enemyStart.y, 'cultist'); enemy.countStats(); this.enemies.add(enemy); } this.enemies.setAll("body.immovable", true); } In the update function - I try to detect the collision between the children in the group like in this example (using 2.4.7): physics&f=group vs self.js&t=group vs self&phaser_version=v2.4.7&; But they wont collide with - just passing trough - each other. Also tried with adding a callback as when I let the player sprite collide with the enemy group like this:, this.enemies, this.collisionHandlerPlayerAndEnemy, null, this);, null, this.collisionHandlerEnemyAndEnemy); And the callback-function will not be called (may it be that this does not even work at all when the case is group to group?). I need someone elses eyes on this. No properties for enemy body is set outside these code blocks.
  5. Hi folks, I'm new to this forum but I was wondering if someone could point me in the right direction or to a tutorial that'll help me out? I can't seem to get the collision detection to work here. This is my code: var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }, true); function preload() { game.load.image('shot', 'assets/sprites/drop.png'); game.load.image('spaceship', 'assets/sprites/spaceship.png'); game.load.image('glass', 'assets/sprites/glass.png'); game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; } var spaceship; var glass; var shot; var cursors; var fireButton; function create() { // Creates 1 single bullet, using the 'shot' graphic shot = game.add.weapon(1, 'shot'); game.physics.arcade.enable(shot); // The shot will be automatically killed when it leaves the world bounds shot.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; // Because our shot is drawn facing up, we need to offset its rotation: shot.bulletAngleOffset = 90; // The speed at which the shot is fired shot.bulletSpeed = -600; spaceship = this.add.sprite(320, 20, 'spaceship'); game.physics.arcade.enable(spaceship); glass = this.add.sprite(320, 310, 'glass'); game.physics.arcade.enable(glass); // Tell the Weapon to track the 'player' Sprite, offset by 14px horizontally, 0 vertically shot.trackSprite(spaceship, 100, 180); cursors = this.input.keyboard.createCursorKeys(); fireButton = this.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR); } function update() { // object1, object2, collideCallback, processCallback, callbackContext game.physics.arcade.overlap(shot, glass, collisionHandler, null, this); spaceship.body.velocity.x = 0; if (cursors.left.isDown) { spaceship.body.velocity.x = -300; } else if (cursors.right.isDown) { spaceship.body.velocity.x = 300; } if (fireButton.isDown) {; } } function collisionHandler(obj1, obj2) { // The two sprites are colliding // shot.kill(); shot.destroy(); console.log("collision"); } function render() { shot.debug(); } If anyone could help that'd be great! Kind regards!
  6. Hey guys... Anybody got on insights on how the mesh.onPhysicsColiide property is supposed to work ??? I have this code to detect when two meshes with physics state enabled collide with each other. Now in the scene... both mesh actually do collide and bounce off each other like it should... but the the mesh.onPhysicsCollide property i set is NOT firing off. Here is code to log the collision event to the console (BUT I GET NOTHING ) // Physcis collision this.mesh.onPhysicsCollide = (collider:BABYLON.AbstractMesh, contact:any) => { console.log("*** HOLY SHIT - I GOT COLLISION ***"); console.log(collider); }; Any thoughts ???
  7. I really need to be able to hook into physics collision detection... There used to be a mesh.onPhysicsCollide that would have worked perfectly for my collision detection system (I basically don't require the imposter filter part for collision detection... I will filter based off mesh.metadata tags). Now using the registerOnPyhsicsCollide DOES NOT WORK without some kind of imposter (even with the otherImposter.length === 0). The problem is the unregister DOES NOT find if you pass null imposter or empty imposter array... you gotta pass an actual imposter to filter or you WONT be able to unregister.... and you will leak. I need basic collision detection support... I will handle (filter) what should be imposter collision event should get dispatched. I suggest the SMALL change to the babylon.physicsImpostor class: /** * Legacy collision detection event support */ public onCollideEvent: (collider:BABYLON.PhysicsImpostor, collidedWith:BABYLON.PhysicsImpostor) => void = null; //event and body object due to cannon's event-based architecture. public onCollide = (e: { body: any }) => { var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body); if (otherImpostor) { // Legacy collision detection event support if (this.onCollideEvent) { this.onCollideEvent(this, otherImpostor); } if (!this._onPhysicsCollideCallbacks.length) return; this._onPhysicsCollideCallbacks.filter((obj) => { return obj.otherImpostors.indexOf(otherImpostor) !== -1 }).forEach((obj) => { obj.callback(this, otherImpostor); }) } } What do you think @Deltakosh @Sebavan @RaananW ... OR Should i just fork my own BabylonJS Toolkit Version of the framework... And i will just use my own build for the toolkit: /Assets/Babylon/Library/babyblon.bjs (Which might not be a BAD idea... At least i would have better control of the main babylonjs library and the API that is necessary for me to make the KOOL toolkit features i have been working on) I dunno ... Please folks... Weigh in your thoughts before i do anything drastic with the toolkit libraries
  8. Hi, I'm using Phaser (2.2.1) to make my first game, a platformer. Arcade physics to do the collision detection; Tiled to make the map. The problem I'm having is that the player occasionally passes through a platform when descending from a higher point (after jumping for example). Here are what I think are the relevant bits of code: Create: this.gravity = 2200;this.blockedLayer ='blockedLayer');,10000,true,'blockedLayer');this.player = this.add.sprite(200,200,'player');this.player.anchor.setTo(0.5,1);this.physics.arcade.enable(this.player);Update:,this.blockedLayer);So to repeat -- it's working most of the time, but 1 jump in 8 results in the player falling down through a platform (including through the floor on occasion). Following the advice in this post I tried playing with TILE_BIAS but it just made the player act freaky around the platforms... Has anyone had this problem before? Any ideas how to fix it much appreciated.
  9. What is the best approach to determining what face of a mesh was hit in a collision? I'm creating a game in which there are very many meshes; they are platforms onto which the player can jump. But if the player hits the side of any platform, he dies. As far as I can think, there are two approaches here: 1. Find some way of determining which vertex set was hit, get the normal to it, and record whether the normal points in the (0,1,0) direction (OK) or otherwise (kills player). However, I can only find a way of telling when two meshes collide. The PhysicsImpostor.registerOnPhysicsCollide callback only tells me which meshes are hit. Perhaps once I have the two meshes there is a way to tell which vertex set of one mesh intersects which vertex set of another - but if such a function exists I couldn't find it. (Closest thing is the PickingInfo returned by AbstractMesh.intersects(Ray) - but that's not quite what I need, as far as I can tell). 2. Add additional meshes to the scene to "cover" the platforms. So I could for example add a plane to the top face of each platform and say that if the player collides with it then he's safe, otherwise if he collides only with the platform then he's not. This approach seems inefficient as it doubles the number of meshes. Also would it even work? Say there is a platform that's a cube, and the player hits the side with normal (0,0,-1). That should kill him, but if he hits it near the top he may also just touch the edge of the cover - which by the logic above would save him. Thanks for any pointers!
  10. After half a day of debugging, I am quite sure the issue is not in my code since it comes directly out of Phaser. I attached a screenshot. The characters collide at the green C marked position. But there is nothing to collide with. The <obj>.body.blocked.left property is set to true >> so they are colliding left This shouldn't be possible. Since there is no object (green mark C) So I debugged the Phaser functions for collision. The call comes out of: (thanks to @Claudiovc ) processTileSeparationX is called from: were I passed in the >tile< parameter to processTileSeparationX and logged it. You can see that in the console window in the screenshot. The data on this tile shows that the ground-tiles are causing the <obj>.body.blocked.left = true. This Tile is marked red T. This is a possible bug. I also tested all the tile data, which you can see is on debug mode. Every tile (debug mode) aligns on the same pixel on the Y axis. So there is no "step" in it. The reason to assume it is a bug is that the collision on the left is called not <obj>.body.blocked.down Any further thoughts or already investigations on that - or am I completely wrong regards **EDIT** You can also test this with collision enabled only for top / bottom, then the floor tiles wont fire the collision. So I assume this is indeed some issue with the collision detection within phaser.
  11. Hi, I need to implement a check that can determine if a bounding box is completely inside a set of bounding boxes. See my attached graphic for a better understanding of the situation. I am thinking of consuming the A to B paths on each axis of the original bounding box using the axes limits of the containing bounding boxes. Then, for each axis, I would store those in an array, sort them by starting point, find if there are overlaps, eliminate them, find gaps (could probably happen if outer bounding boxes are not adjacent to each other) and if none are there, look if the total length is the length of the object bounding box. If this is the truth for every axis, then I can be sure that the item is completely inside the valid area. The only thing I am worried about is that this can become quiet slow. Since this is usually an edge case, I would first go through all container bounding boxes and see if the object is completely inside one of them. Only if that is not true, I need to do the more complex check. Any ideas on different, maybe faster algorithms? Regards Jacques
  12. I have been working with Phaser for about 6 months now, and have recently purchased the Box2D plugin, and for the most part its great, although I am having a few basic problems with spawning the sprite with an appropriately sized body, then applying a continuous velocity. Below is the offending function. First a sprite is spawned from a loaded atlas (the zombie), but unfortunately the sprite is way too big (or my game is too small, one of them) and needs to be scaled down to a 1/4 of its original size. I found a question elsewhere on here where someone (it may have even been Rich) gave an answer to define the body separately, then reattach it to the sprite and the sprite to it. This appears to work fine-ish, giving me a body that is registered as the sprite's and collides properly etc etc. On spawn the zombie plays an anim of pulling itself out of the ground (the spawn anim), and then when that is completed it should play the walk animation, then actually move. The commented section within the OnComplete callback shows all of the different methods of getting something to move in Box2D the internet can give me, but none of them work. function spawnZombie(x, y){ var zombie = zombies.create(x, y, 'zombie'); zombie.anchor.setTo(0.5, 0.5); zombie.scale.setTo(0.25, 0.25); var zomBody = new Phaser.Physics.Box2D.Body(, null, x, y, 0.5); zomBody.setRectangle(30, 50, 0, 0, 0); zombie.animations.add('spawn', Phaser.Animation.generateFrameNames('appear/appear_', 1, 11, '', 1), 7, false); zombie.animations.add('walk', Phaser.Animation.generateFrameNames('walk/go_', 1, 10, '', 1), 7, true); zomBody.sprite = zombie; zombie.body = zomBody;'spawn');{'walk'); //zombie.body.velocity.x = -100; //zombie.body.moveLeft(100); //zomBody.moveLeft(100); //zomBody.velocity.x = -100; console.log(zombie); }, this); } Personally I think that the problem lies with the body being set as it is, as this method feels like a buggy workaround to me. The only symptom of the problem I can see within the sprite object is that setting the velocity actually does nothing, whereas elsewhere in the code it works as expected. I wouldn't be exaggerating if i said i had spent 6 hours on this problem, and I'm about 2 hours away from quitting my job forever and ritually burning my PC. Any help at all would be great, cheers.
  13. Hi all, I'm making a mobile game and looking for the most efficient way of going about coding the following. Any comments would be most welcome 1. A solid background image Is this just a sprite of an optimized bitmap? Or is there a special method for bg images that keeps them as efficient as possible. 2. Generate a lot of balls (sprites) that bounce around the screen (Currently created a group for the balls and MANUALLY checking for boundary collisions to avoid the overhead of any physics engine). Am I being too harsh here? Will ARCADE physics do a better job of it, efficiency wise? 3. I need to check collisions with the touch/click co-ordinates at a given moment with all these balls, even if they overlap, a click will be detected regardless of layers. My initial thoughts are to engage quad trees to elect candidates for running collision detection on. I have this function too, to detect clicks in a circle: // Check if the input is within a circular radiuscheckCollision: function(ball, inputX, inputY) {var radius = ball.width/2var centerX = ball.x+radius;var centerY = ball.y+radius;if(Math.sqrt((inputX-centerX)*(inputX-centerX) + (inputY-centerY)*(inputY-centerY)) < radius) {return true;} else {return false;}},I'm having trouble relating the sprites in a group to candidates that are retrieved from a quadtree, is the quadtree built into groups? Say if a candidate came back from the quadtree, and collision was true, how would I kill the sprite from the group? Any pointers would be great! Thanks guys, Phaser is really great to work with.
  14. Hello all, I'm trying to make a "game" in which you drag sticks from a pool and you position them on the screen. (I'm basicaly creating a cuisenaire program). The sticks have to be restrained in the underneath tilemap and also cannot overlap with each other. Every stick has a sprite.input.enableDrag(); sprite.input.enableSnap(30, 30, true, true); So it can be draggable. Also, I whenever the user drags a stick from the pool, I clone a stick there so he can drag another one later on. How can I instruct phaser to watch for collisions between all sticks? If I put them on a group, I loose the input.enableDrag on every stick. If I don't have them on a group, how can I reference them to watch for collisions with each other? Thank you
  15. I am making a game, everything works except the physics system? Collisions and Gravity are in the code but don’t seem to work. Using breakpoints, it gets to all the pieces of code but never actually works. I have tried to frantically make it work (Thats why theres so much physics code in the file). Can anyone please help me? This is the code that I think you will need: This is all of the code together: Thanks.
  16. Hey there, my game consists of a player implemented with P2 and enemies implemented with Arcade physics (for better performance, since the AABB is sufficient for them). How can I detect collision between the Arcade bodies and the P2 body/bodies ? (The point is: I want the enemies to bounce away) OR: I've read in some other thread, that P2 offers AABB. I've searched the Phaser docs, but I didn't find anything helpful. Can you recommend a way to implement the described above only with P2, without affecting performance? Thank you guys in advance!
  17. I'm trying to detect a possible collision between objects that could be stationary or moving in any direction (angle). 1. I want the object to be notified when a particle/object is inbound for collision. Essentially, I want to introduce AI where the object will take action when it is shot at or an enemy is approaching. 2. Another use-case is for scanning. I'd like an entity to be able to spot its enemies and get info like distance, velocity, type, etc. I've read through the documentation, examples, posts on the forum and searched online, but I've clearly missed something. Does anyone know a way to accomplish the above? Thanks!
  18. Hi, This is my first post. I have done a search for this but I haven't found anything that specifically answers what feels like a basic question. I'm developing my first game using phaser, it basically involves a character running along a rope and collecting things. The character jumps up and down and the objects come on at two different heights. It's a pretty basic game. So, what I'd like to know is: Is it possible to have physics bodies pass through one another. Specifically what I'd like is to be able to register the characters collision with the object but then have the object pass through the character and carry on off the screen. By scanning these forums I discovered 'overlap' instead of 'collision' which has helped but the objects still don't pass through the character. I'm aware that this is disobeying the laws of physics! But I had expected that there would be an easy way to do this - I've tried setting the body to null and a few other things but I can't find a solution that works. Any help would be much appreciated.
  19. Hello everyone! I am making a game and i have some objects with triangular shape. I use p2js just for collision detection with onBeginContact (everything else is handled manually, like movement etc.). So i am wondering if there is a less expensive way to detect polygon collision. Thanks
  20. Hi, I am working on an RPG like game. I am using an ASCII Map drawn by an algorithm that I found online. So right now my objective is getting collision detection working with the player. However, when I try to add the text to a group it works, but when the player hits against any part of the map the hit detection does not work. So i am kind of stuck. Please help me! Thanks in advance Here is my code: // font sizevar FONT = 22;//var Height and Width for the Map's COLS and ROWSvar HEIGHT = 550;var WIDTH = 800;//Key variable set upvar cursors;var spaceKey;//offset for map's positionvar MAP_OFFSET = 2.38;//Game's height and widthvar gameHeight = 600, gameWidth = 800;//text for the mapvar text;//Style of textvar style = { font: FONT + "px monospace", fill:"#fff"};// map dimensionsvar ROWS = HEIGHT/FONT;var COLS = WIDTH/FONT/0.61;// number of actors per level, including playervar ACTORS = 10;// the structure of the mapvar map;//group the map objectsvar mapGroup; // the ascii display, as a 2d array of charactersvar asciidisplay;// initialize phaser, call create() once donevar game = new Phaser.Game(gameWidth, gameHeight, Phaser.CANVAS, '', { preload: preload, create: create, update: update});var graphics;function preload() { /* Using a square instead for now don't like the charcter */ //game.load.spritesheet('dude', 'assets/dude.png', 32, 48); graphics =,0); graphics.beginFill("0xFF700B", 1); graphics.lineStyle(2, 0x0000FF, 1); graphics.drawRect(20, game.height - 550, 25, 25); graphics.endFill();}function create() { //Start game physics game.physics.startSystem(Phaser.Physics.ARCADE); // initialize map initMap(maze(ROWS, COLS)); // initialize ascii display asciidisplay = []; for (var y=0; y<ROWS; y++) { var newRow = []; asciidisplay.push(newRow); for (var x=0;x<COLS;x++) newRow.push(initCell('', x, y + MAP_OFFSET)); } drawMap(); // the map group mapGroup =; mapGroup.add(text); console.log(mapGroup); game.physics.arcade.enable(mapGroup); player = game.add.sprite(0, 0); player.addChild(graphics); game.physics.arcade.enable(player); cursors = game.input.keyboard.createCursorKeys();}function update() { player.body.velocity.x = 0; player.body.velocity.y = 0; if (cursors.left.isDown) { player.body.velocity.x = -150; //'left'); } else if (cursors.right.isDown) { player.body.velocity.x = 150; //'right'); } else if (cursors.up.isDown) { //Move up the screen player.body.velocity.y = -150; } else if (cursors.down.isDown) { //Move down the screen player.body.velocity.y = 150; } game.physics.arcade.collide(player.body, mapGroup.child, stopPlayer);}function initCell(chr, x, y) { // add a single cell in a given position to the ascii display text = game.add.text(FONT*0.6*x, FONT*y, chr, style); return text;}//creating the mapfunction initMap(m) { // create a new random map map = []; for (var j= 0; j<m.x*2+1; j++) { var line= []; if (0 == j%2) for (var k=0; k<m.y*4+1; k++) if (0 == k%4) line[k]= '+'; else if (j>0 && m.verti[j/2-1][Math.floor(k/4)]) line[k]= ' '; else line[k]= '-'; else for (var k=0; k<m.y*4+1; k++) if (0 == k%4) if (k>0 && m.horiz[(j-1)/2][k/4-1]) line[k]= ' '; else line[k]= '|'; else line[k]= ' '; if (0 == j) line[1]= line[2]= line[3]= ' '; if (m.x*2-1 == j) line[4*m.y]= ' '; map.push(line.join('')+'\r\n'); } return map.join('');}function drawMap() { for (var y = 0; y < ROWS; y++) for (var x = 0; x < COLS; x++) asciidisplay[y][x].text = map[y][x];}function maze(x,y) { var n=x*y-1; if (n<0) {alert("illegal maze dimensions");return;} var horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [], verti =[]; for (var j= 0; j<y+1; j++) verti[j]= [], here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)], path = [here], unvisited = []; for (var j = 0; j<x+2; j++) { unvisited[j] = []; for (var k= 0; k<y+1; k++) unvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1)); } while (0<n) { var potential = [[here[0]+1, here[1]], [here[0],here[1]+1], [here[0]-1, here[1]], [here[0],here[1]-1]]; var neighbors = []; for (var j = 0; j < 4; j++) if (unvisited[potential[j][0]+1][potential[j][1]+1]) neighbors.push(potential[j]); if (neighbors.length) { n = n-1; next= neighbors[Math.floor(Math.random()*neighbors.length)]; unvisited[next[0]+1][next[1]+1]= false; if (next[0] == here[0]) horiz[next[0]][(next[1]+here[1]-1)/2]= true; else verti[(next[0]+here[0]-1)/2][next[1]]= true; path.push(here = next); } else here = path.pop(); } return {x: x, y: y, horiz: horiz, verti: verti};}function stopPlayer() { player.body.velocity = 0; console.log("stopped");}Thank You for your help in advance!
  21. Hi to all, This question regards collision-detection on a terrain and also on other meshes. Going through this example here: And playing with it in the playground and even on my local server, everything works as it should, collision detection is enabled and the camera does not fall through the mesh and it also hits the box. This is really good for an FPS. The issue comes when one uses this same technique without a camera, like so: scene.gravity = new BABYLON.Vector3(0, -0.5, 0); scene.collisionsEnabled = true; //terrain: var ground = BABYLON.Mesh.CreateGroundFromHeightMap("ground", "DoubleBasin_big/DoubleBasin_big.png", 100, 100, 100, 0, 12, scene, true); var groundMaterial = new BABYLON.StandardMaterial("groundMat", scene); groundMaterial.diffuseTexture = new BABYLON.Texture("tiles-56/arroway.de_tiles-56_d100.jpg", scene); groundMaterial.diffuseTexture.uScale = 5.0; groundMaterial.diffuseTexture.vScale = 5.0; ground.material = groundMaterial; ground.checkCollisions = true;//wall:var Mur = BABYLON.Mesh.CreateBox("Mur", 1, scene);Mur.scaling = new BABYLON.Vector3(15, 6, 1);Mur.position.y = 3.1;Mur.position.z = 20;Mur.checkCollisions = true;//loaded character: meshPlayer.checkCollisions = true; meshPlayer.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5); meshPlayer.ellipsoidOffset = new BABYLON.Vector3(0, 2, 0); meshPlayer.applyGravity = true; That would be good for a third person type of thing. The code is from dad72's demo here: It works fine on that link, however when I downloaded the source and ran it on the local server, everything just falls through the terrain's mesh. The code is unchanged with the exception of using different materials and a different heightmap. Is there something missing somewhere on my part, once the code is run locally? There isn't any physics, just in-built babylon.js collision. This example from my perspective is extremely impressive, as it shows how easy it is to build a game. The only thing that's left is just adding a story-line with different characters, environments and so on! This is a really amazing engine! Thanks in advance.
  22. Is there any way to just trigger the action for an Intersect Mesh event regardless of which mesh collided with my object? bouncy_ball.actionManager.registerAction(new BABYLON.ExecuteCodeAction( { trigger: BABYLON.ActionManager.OnIntersectionEnterTrigger, parameter: cube_bottom }, function () { onCollision(bouncy_ball, cube_bottom);})); bouncy_ball.actionManager.registerAction(new BABYLON.ExecuteCodeAction( { trigger: BABYLON.ActionManager.OnIntersectionExitTrigger, parameter: cube_bottom }, function () { bouncy_ball.hasCollision = false; }));I want to trigger the function "onCollision" every time my ball has a collision with anything at all. Inside "onCollision" I want to check if the object was below the ball, so I also need to know the object the ball collided with for the function call. Is there a way to set the trigger-parameter to "any" and can I still find out which it was then?
  23. Hey umm, lots of questions on collisions (collision-detection) so I thought I'd post some of my experience so far. I'm far away from being, javascript competent or math competent so most of it I've found somewhere else and used. Firstly acknowledging Pythagoras and the nice people at Easel js = Lanny Mc Nee. var minDistance = 20;var dist = Math.sqrt(distX * distX + distY * distY);if (dist <= minDistance) { // hit}Beautiful isn't it? So simple. If I were smarter, or had the time, I would simply code this formula into all my colliding entities. I've never tried this one, the 'SAT'. Does that mean I sat on something? I might have, but it stands for Separating Axis Theorem. I can refer immediately to David Geary's book 'Core HTML5 Canvas'. Here is the SAT example.. And here is a link for all the code examples from the book online.. Here is a code example for a square collision - sorry no attributes - can't remember where I got it, and have changed it a lot since I found it. function squareBump(x1, y1, w1, h1, x2, y2){if(x1 <= x2 && x1+w1 >= x2) &&(y1 <= y2 && y1+h1 >= y2){return true; }}//Using square collisionif(squareBump(teddy.x, teddy.y, 128, 128, cupcake.x, cupcake.y)){ // The Rectangle collision //teddy bumps into cupcake here }O well the above might be wrong in itself but hopefully you can see the rectangle logic. Now here is circular collision detection which I've used on my own site. function bumpTeddy (xPos, yPos, radius){ //CIRCULAR COLLISION var distX = xPos - teddy.x; var distY = yPos - teddy.y; var distR = radius + 58; if (distX * distX + distY * distY <= distR * distR){ return true } }Opps! Sorry more dumb code, but we can see that the 'radius' is a new argument where the rectangle had four arguments. now we have three and determine our radius. + or - . I've used this collision framework made for easeljs ... Good for pngs - don't worry about frameworks, just dive into the code and grab it ! Ok Then, from what I've found so far with collision detection, remember I'm just a nooobeee, hack it up until get a result type coder. 1/ Get the code and squash it into your application until it works, only then try to understand it. 2/ Spend a lot of time fiddling with the collisions you have - that way you could get a new idea. 3/ If you have a successful collision, tweak and work it until it's perfect before looking for other code. No not presuming to give advice except to myself. Thank you for your patience.
  24. I have no idea how to check for collision on only a small part of an image or sprite. For example, in the Image below, how would I detect collision with the sword in the red circle, but not detect collision with anything else in the blue square. I just want the sword to kill enemies and not the rest of his body or the white space above and below the sword. Another example, if my character is standing over a gap, my code sees his width as the width of his whole image (from his sword to the other arm) , and so he doesn't fall in the gap. How could I do collision detection with only a small part of the image? Could someone tell me what the technique is called or send me to an article to read. I don't even know where to begin looking. Thanks! PS. I am learning WITHOUT frameworks or libraries. I would like any help with just vanillaJS and later I'll learn a library.
  25. Hi Folks, I am new to Phaser framework. I have 6 sprites which are draggables. The codebase is as under: var circle = game.add.sprite(64.0, 55.0, "circle");circle.anchor.setTo(0.5, 0.5);var triangle = game.add.sprite(151.3, 55.3, "triangle");triangle.anchor.setTo(0.5, 0.5);var box = game.add.sprite(63.15, 118.55, "box");box.anchor.setTo(0.5, 0.5);var penta = game.add.sprite(151.25, 122.9, "penta");penta.anchor.setTo(0.5, 0.5);var plus = game.add.sprite(62.95, 179.25, "plus");plus.anchor.setTo(0.5, 0.5);var rect = game.add.sprite(151.4, 182.9, "rect");rect.anchor.setTo(0.5, 0.5); var arrItem = new Array(circle, triangle, box, penta, plus, rect); for (var i = 0; i < arrItem.length; i++) { var oItem = arrItem[i]; oItem.inputEnabled = true; oItem.input.enableDrag(false, true);,this);,this);}And the droppables code are as under: for (var i = 0; i < currentDesign.shape.length; i++) { var shape = currentDesign.shape[i]; var aShape = game.add.sprite(shape.x, shape.y, "circle"); shape.inputEnabled = true; aShape.anchor.setTo(0.5, 0.5); player.members.arrDesignItems.push(aShape);}How to do collision detection? Please guide step by step. Regards Duke Ranjan