Search the Community
Showing results for tags 'Collision'.
-
Hello, I'm new to Babylon.js. I was wondering is there a way to trigger event when camera and mesh intersects? I tried put camera in to a box, and when these two meshes(camera container and object) met I want to trigger some events, but it's not working as I thought. camera mesh collisions event | Babylon.js Playground (babylonjs.com) Is there any other possible solution? Thanks!
-
- babylon
- babylon.js
-
(and 2 more)
Tagged with:
-
Hey community, this is my first post here, I am sharing my scene in which I have used bounce and collision effect of phaser 3 , I have marked comments in order for understanding and reference purposes. The code I have laid down is as follows: window.onload = () => {//creating game window. class MainScene extends Phaser.Scene { preload() {// the following function preloads the image asset required in scene this.load.image("bird", "bird.png"); } create() { this.player = this.add.group();//grouping the sprite in order to load them at different positions this.time.addEvent({ delay: 1000, loop: true, callback: () => this.addBall() })//calling back addBall function after this.physics.add.collider(this.player, this.player);//setting collider object between every object } update() { if (this.player.getChildren().length > 10) {// if qty of objects/player is >10 const bird = this.player.getFirstAlive();//getting 1st instance of player this.tweens.add({targets: [bird], alpha: 0, duration: 500, onComplete: () => bird.destroy()});//deleting first instance of player } this.player.getChildren().forEach(bird => bird.setAngularVelocity(bird.body.velocity.x * 1));//to produce spiral motion } addBall() { const bird = this.physics.add.sprite(game.config.width / 3, 150, "bird");//assigning sprite to bird vairable this.player.add(bird);//assigning ball to bird.setBounce(0.7);//setting bounce value , bird.setDrag(1);//setting drag value bird.setCollideWorldBounds(true);//to enable collision setting bounds bird.setVelocity(Phaser.Math.Between(-800, 800), 0);//setting velocity bird.setScale(Math.random());//so that the objects are of random, not same size, } } const game = new Phaser.Game({ type: Phaser.AUTO, width: 600,//frame width height: 600,//frame height physics: { default: 'arcade', arcade: { gravity: {y: 1000},//setting up gravity value } }, scene: [MainScene] }); }; So thats how my scene looks and all the birds disappear after a certain time, as mentioned in the code, Feel free to suggest what more I shall improve upon in order to grow and develop, and how you feel of this scene. Thank You
-
Hello, I'm using Phaser 3 and the physics engine matter. I need to call a function when one object collides with a particular object. For example I have a tank, barrels, hearts. Then there will be bullets, other tanks, some other objects. You need to call the function when the tank collides with the barrel, it should explode, and if it collides with the heart, it will replenish life. this.matter.world.on('collisionstart', function (event) { bangBarrel(); }); this method calls the function in any collision. How to trigger the function when the tank collide with the barrel, and how to trigger the function when the tank collide with the heart?
-
Hi, I saw the code presented in the link https://playground.babylonjs.com/#1NQTNE#11 and played many times. I felt "moveWithCollisions" is full of magic . it seems that with the help of "movewithCollisions" the mesh can smartly move and move little by little and finally manage to find its path to reach its destination. I checked the code but was not able to figure out how to use it exactly, there is few comment or remarks to tell what's the purpose of some important lines . so I listed these important lines that I didn't understand as below. can anyone please help to explain what's the purpose of these critical lines? (please notice that I use "//" to bring up what my question is ) // move to clicked coordinates ............ if(meshPlayer.destination) { var moveVector = meshPlayer.destination.subtract(meshPlayer.position); if (moveVector.length() > 1.1) { //1.why use 1.1 ,other than 2.2 or 0.8 or any length else? is it related to the player size 1 while downcasting a ray ? moveVector.y = GRAVITY; //2.GRAVITY is -0.5 as defined earlier, but why moveVector.y must be -0.5? what's the purpose to assign moveVector.y ? moveVector = moveVector.normalize();//3.what's the purpose of "normalize"?what's the benefit of doing this? is this line mandatory? moveVector = moveVector.scale(0.2); //4.why to shrink the moveVector to 1/5 of its original size? why not 0.1 or 2 or some number else? if(meshFound.distance > 1.1){moveVector.y = GRAVITY;} //5.why 1.1 again? meshPlayer.moveWithCollisions(moveVector); } else { meshPlayer.destination = null; } } .......... It's really appreciated for your time. Edit Your content will need to be approved by a moderator
-
- avoid obstables
- subtract
- (and 5 more)
-
I just want to convert something like this: // In create function var graphics = this.add.graphics(); graphics.fillStyle(0x00605F, 1); graphics.fillRectShape(new Phaser.Geom.Rectangle(0, 20, 470, 70)); graphics.fillRectShape(new Phaser.Geom.Rectangle(250, 0, 70, 200)); Into some type of sprite (then to a pixels array) or pixels array. But how would I do that? And how would I get the pixels of a sprite like this: var player = this.add.existing(new Player(this, 300, 200, "player")); (Why am I asking this? Well I want to create this: https://www.khanacademy.org/computer-programming/pixelated-collision-experiment/4899192330158080 in Phaser 3)
-
Hi, I was using matter physics and tried to check collisions from a lot of objects and then I got some issues. The problem: I have a lot of objects (called them "luz" in the code) and I want to release them on air and making them fall. Then when they touch the floor I want to trigger something: - if it is a even object: I want to reduce its Alpha to 30%. - if is an odd object: I reduce their scale by half. Currently I'm handling this situation in my real project by checking update() { if (luz[i].y > floor.Y) { /* do something */ } /*...*/ } but I'm looking for a better and more flexible and robust solution. So here is my code: class GameScene extends Phaser.Scene { constructor () { super('GameScene'); } preload() { this.load.image('luz', 'luz.png'); } create() { // create elements on air for (var i=1; i<=7; i++) { var luz = this.matter.add.image(i*100 + 10, 50, 'luz') luz.body.label = i%2 == 0 ? "even luz" : "odd luz" } // add the floor this.matter.add.rectangle(400, 550, 800, 50, {isStatic: true}).label = "floor" // check collisions this.matter.world.on('collisionstart', function (event, object1, object2) { // this only prints the first object console.log(object1.label + " collides with " + object2.label) switch (object1.label) { case "odd luz": object1.gameObject.alpha = 0.3; break; case "even luz": object1.gameObject.setScale(0.5); break; } }) } } Live example here: https://codepen.io/akuma119/pen/zYvKzgW Video showing the problem: https://i.imgur.com/jU7UiaW.mp4 My questions are: - Am I handling collisions correctly? is this the proper way? - Should I implement my own collision checking system? - Is checking by label a bad design/practice? Thank you for your time and help!
-
I am creating a platformer with Phaser3 and I am using Matter for my physics engine. I have loaded my tilemap/set into the world, however, I don't know if the collisions are working because since I have added in this code, my sprite has disappeared. Why is this? How do I get my sprite to appear again so that I can make sure he collides with the tiles? //Create tilemap const map = this.make.tilemap({key: 'map'}); //Create tileset const tileset = map.addTilesetImage('tiles'); const platforms = map.createDynamicLayer(0, tileset, 0, 0); map.setCollisionByExclusion([-1, 0]); this.matter.world.convertTilemapLayer(platforms); //Update the game at 30Hz this.matter.world.update30Hz(); //Get hitboxes this.shapes = this.cache.json.get('shapes'); //Set boundaries for physics this.matter.world.setBounds(0, 0, game.config.width, 750); //Player this.hero = this.matter.add.sprite(0, 0, 'sheet', 'run_right/0013', {shape: this.shapes.s0013}); //Don't want him rotating in the air this.hero.setFixedRotation(); //Set our variable to do calculations heroSize = this.hero.width;
-
Hello friends, I am new to the forum, I would like you to help me solve a slightly urgent problem, I am putting together a game with Phaser, I try to collide one image with another, until there is easy, the problem arises because one of the bodies has an animation with a tween, and when making a collision with another body, don't do it, keep going down, has someone happened to you ?, I show you the code var config = { type: Phaser.AUTO, width: 1200, height: 675, parent: 'Fondo', transparent: true, pixelArt: true, physics: { default: 'arcade', arcade: { gravity: { y: 1000 }, debug: false } }, scene: { preload: preload, create: create, update: update } }; var player; var cursors; var cofreup; var stars; var fondo; var platforms; var plataforma2; var colup; var suelo; var move = 0; var game = new Phaser.Game(config); function preload() { this.load.image('star', '../juego4/img/star.png'); this.load.image('fondo1', '../juego4/img/bg.png'); this.load.image('colision', '../juego4/img/plataformas/colision.png'); this.load.image('colision2', '../juego4/img/plataformas/colision.png'); this.load.image('plataforma1', '../juego4/img/plataformas/img-07.png'); this.load.image('plataforma2', '../juego4/img/plataformas/img-08.png'); this.load.image('cofre1', '../juego4//img/plataformas/img-15.png'); this.load.image('baul', '../juego4/img/plataformas/img-16.png'); this.load.image('ground', '../juego4/img/platform.png'); this.load.spritesheet('dude', '../juego4/img/dude.png', { frameWidth: 64, frameHeight: 98 }); } function create() { suelo = this.physics.add.staticGroup(); suelo.create(1, 690, 'ground').setScale(100, 1).refreshBody(); //colisiones// col = this.physics.add.staticGroup(); //*baul col.create(500, 570, 'colision').setScale(12, 2).refreshBody(); //*plataformas col.create(80, 170, 'colision').setScale(15, 2).refreshBody(); col.create(610, 370, 'colision').setScale(25, 2).refreshBody(); col.create(650, 150, 'colision').setScale(25, 2).refreshBody(); col.create(80, 476, 'colision').setScale(12, 2).refreshBody(); col.create(350, 280, 'colision').setScale(12, 2).refreshBody(); col.create(1100, 180, 'colision').setScale(12, 2).refreshBody(); col.create(980, 475, 'colision').setScale(12, 2).refreshBody(); //*cofres btn = this.physics.add.staticGroup(); btn.create(800, 570, 'colision').setScale(12, 2).refreshBody(); //*plataformas //Colisiones movieminto// //baul cofre = this.physics.add.staticGroup(); cofre.create(500, 610, 'baul'); //Plataformas grandes platforms = this.physics.add.staticGroup(); platforms.create(600, 400, 'plataforma1'); platforms.create(50, 200, 'plataforma1'); platforms.create(650, 180, 'plataforma1'); //Plataformas pequeñas platforms2 = this.physics.add.staticGroup(); platforms2.create(80, 500, 'plataforma2'); platforms2.create(350, 300, 'plataforma2'); platforms2.create(1100, 200, 'plataforma2'); platforms2.create(980, 500, 'plataforma2'); //Imagen cofres // cofreup = this.add.image(250, 500, 'cofre1'); this.tweens.add({ targets: cofreup, y: 100, paused: false, physics: true, collider: true, duration: 5000, ease: 'Sine.easeInOut', yoyo: true }); //Muñecos player = this.physics.add.sprite(100, 10, 'dude'); player.setBounce(0.1); player.setCollideWorldBounds(true); //Animacion personaje this.anims.create({ key: 'left', frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }), frameRate: 10, repeat: -1 }); this.anims.create({ key: 'turn', frames: [{ key: 'dude', frame: 4 }], frameRate: 12 }); this.anims.create({ key: 'right', frames: this.anims.generateFrameNumbers('dude', { start: 6, end: 8 }), frameRate: 10, repeat: -1 }); cursors = this.input.keyboard.createCursorKeys(); stars = this.physics.add.group({ key: 'star', repeat: 11, setXY: { x: 12, y: 0, stepX: 70 } }); stars.children.iterate(function (child) { child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8)); }); this.physics.add.collider(player, col); this.physics.add.collider(player, suelo); this.physics.add.collider(suelo, cofreup); this.physics.add.collider(stars, suelo); this.physics.add.collider(player, cofreup); this.physics.add.collider(stars, platforms); this.physics.add.overlap(player, stars, collectStar, null, this); this.physics.add.overlap(player, btn, call, null, this); } function update() { if (cursors.left.isDown) { player.setVelocityX(-160); player.anims.play('left', true); } else if (cursors.right.isDown) { player.setVelocityX(160); player.anims.play('right', true); } else { player.setVelocityX(0); player.anims.play('turn'); } if (cursors.up.isDown && player.body.touching.down) { player.setVelocityY(-500); player.anims.play('up', true); } //Animacion Cofre // cofreup.x = 220 + Math.cos(move) * 1; // cofreup.y = 460 + Math.sin(move) * 100; // move += 0.03; } function collectStar(player, star) { star.disableBody(true, true); } function call (player, btn) { Tween.stop(); }
-
Example: https://jsbin.com/cakorijiqi/1/edit?js,output Physics.ARCADE collision trouble. Sprite fall through the another sprite if hight velocity. If you change the value from 500 to 100 in the velocity, then the problem does not occur. this.boxGroup.setAll('body.velocity.y', 500); What is the cause of the problem? And I have noticed. If the swap these lines (#2, #3), the box to fall through the floor. function update() {//#1 game.physics.arcade.collide(this.boxGroup); //#2 game.physics.arcade.collide(this.floor, this.boxGroup);//#3 }//#4 Sorry for my English. Thanks.
- 3 replies
-
- physics.arcade
- collision
-
(and 1 more)
Tagged with:
-
I have a group that contains a large number of children that are P2 physics objects. When I tween the group the sprites all move correctly, but their collisions occur in the position they were prior to the tween. Is there a good way to update the position of the bodies of all the children? Heres some super simplified code incase it helps: game.physics.startSystem(Phaser.Physics.P2JS); const collisionGroup1 = game.physics.p2.createCollisionGroup(); const collisionGroup2 = game.physics.p2.createCollisionGroup(); const targetsGroup = game.add.group(0,0); const ammoGroup = game.add.group(0,300); const target1 = targetsGroup.create(0,0, "key"); const target2 = targetsGroup.create(50,0, "key"); game.physics.enable(target1, Phaser.Physics.P2JS); game.physics.enable(target2, Phaser.Physics.P2JS); target1.body.setCollisionGroup(collisionGroup1); target1.body.collides(collisionGroup2); target2.body.setCollisionGroup(collisionGroup1); target2.body.collides(collisionGroup2); const bullet = ammoGroup.create(0,0, "key2"); game.physics.enable(bullet, Phaser.Physics.P2JS); bullet.body.setCollisionGroup(collisionGroup2); bullet.body.collides(collisionGroup1); game.add.tween(targetsGroup.position).to( {y: "-100"}, 300, Phaser.Easing.Quadratic.Out, true ); Any help would be greatly appreciated, cheers
-
Hello everyone, first time here (so might excuse if its the wrong section) but I'm fricking desperate at the moment. I'm trying for about 2 days now to get my player to collide with my "Obstacle" tilemap layer. I looked at almost every post about this here or elsewhere but I can't get it to work. It might be a simple thing but I can't find whats wrong and I want to throw my pc out of the window now. So maybe one of you guys have an idea and can help me. Any help is appreciated. The code is the Following: var game = new Phaser.Game(255, 255, Phaser.AUTO, '', { preload: preload, create: create, update: update }); var player; var speed = 2; var floor; var walls; var obsts; var map; function preload() { game.load.spritesheet('player','assets/player_spritesheet.png', 48,48); game.load.image("tileset", "assets/tileset.png"); game.load.tilemap( "map", "assets/test_map.json", null, Phaser.Tilemap.TILED_JSON ); // Phaser.Canvas.setSmoothingEnabled(this.game.context, false); this.game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE; this.game.scale.setUserScale(3, 3); this.game.renderer.renderSession.roundPixels = true; Phaser.Canvas.setImageRenderingCrisp(this.game.canvas); } function create() { // Create map map = game.add.tilemap("map", 48, 48, 16, 16); map.addTilesetImage('tileset'); // Use layers floor = map.createLayer('Floor'); walls = map.createLayer('Walls'); obsts = map.createLayer('Obstacles'); map.setCollisionBetween(1,1000); // create player player = game.add.sprite(50,50,'player'); // all physics related stuff game.physics.startSystem(Phaser.Physics.ARCADE); game.physics.enable(player, Phaser.Physics.ARCADE); player.body.setSize(10, 14, 2, 1); player.body.collideWorldBounds = true; // walk animations player.animations.add('idle',[0,1,2],10,true); player.animations.add('walk_right', [12,13,14,15],10,true); player.animations.add('walk_left', [20,21,22,23],10,true); player.animations.add('walk_down', [8,9,10,11],10,true); player.animations.add('walk_up', [16,17,18,19],10,true); //attack animations player.animations.add('attack_down', [24,25,26,27],10,true); player.animations.add('attack_right', [28,29,30,31],10,true); player.animations.add('attack_left', [32,33,34,35],10,true); player.animations.add('attack_up', [36,37,38,39],10,true); player.animations.play('idle'); game.camera.follow(player); } function update() { game.physics.arcade.collide(player,obsts); player.body.velocity.set(0); // Walk mechanic if(game.input.keyboard.isDown(Phaser.Keyboard.A)) { player.animations.play('walk_left'); player.x -= speed; } else if (game.input.keyboard.isDown(Phaser.Keyboard.D)) { player.animations.play('walk_right'); player.x += speed; } if(game.input.keyboard.isDown(Phaser.Keyboard.W)) { player.animations.play('walk_up'); player.y -= speed; } else if (game.input.keyboard.isDown(Phaser.Keyboard.S)) { player.animations.play('walk_down'); player.animations.stop; player.y += speed; } // attack mechanic if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { player.animations.play('attack_left'); } if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { player.animations.play('attack_right'); } if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) { player.animations.play('attack_up'); } if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { player.animations.play('attack_down'); } //jump back to idle when not walking or attacking else if ( !game.input.keyboard.isDown(Phaser.Keyboard.A) && !game.input.keyboard.isDown(Phaser.Keyboard.D) && !game.input.keyboard.isDown(Phaser.Keyboard.W) && !game.input.keyboard.isDown(Phaser.Keyboard.S) && !game.input.keyboard.isDown(Phaser.Keyboard.UP) && !game.input.keyboard.isDown(Phaser.Keyboard.DOWN) && !game.input.keyboard.isDown(Phaser.Keyboard.LEFT) && !game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)){ player.animations.play('idle'); } } Also if you see any other mistakes, feel free to send suggestions to this as well. Thank you in advance. Kind regards
-
Hey guys, I have searched all over to figure this our but no luck. How do I enable the debug to show the bounding/collision boxes on sprites in Phaser 3? this was pretty easy to do in Phaser 2 but I dont see any docs on how to do this for 3. Thanks!!!
-
I'm having an issue with collision. While messing around with terrain, I wanted to make a house, for said terrain. I made a little hexagonal house and exported a STL (I use sketchup web). It imported just fine, but I can't get any collision. My test site is here : (giv0.gitlab.io/Fpoy). I use gitlab because I love the Gitlab web ide and github has nothing like it. Thanks for any help, but if possible, I also need to size it down. I could probably do that on my own, but any efficient was is helpful. Ignore the terrain you spawn on, I was testing height maps and mixmaps and textures. Thanks in advance!
-
I've taken the SpaceInvaders example project and extended it - added different enemy types with animations, a different player, also with animations. I'm in the process of adding the three 'walls' or 'barriers' that were in the original game. I've set up each wall as a separate instance of a class that extends me.Container. Each container holds 4 rows of 12 images in a grid, similar to how the enemies are stored in a container with a grid. Currently all the walls are rendering properly, but it seems like the quad for each wall is offset to the midpoint of the wall (along the x axis). So when I fire, into visually what appears to be empty space, I'm actually hitting and removing a piece of the wall. See the attached gif to get an idea of what the issue is, I have debugging enabled so that you can see the boundaries for each piece of the wall and the walls themselves. The left edge of the collision quad for the wall container seems to be placed horizontally in the middle of the wall, instead of at the left edge. Am I missing something - a parameter for defining the left of the quad? Here's a snippet from play.js, the ScreenObject. onResetEvent: function() { ... var wallY = me.game.viewport.height - 140; console.log("Creating Left Wall"); this.leftWall = new game.Wall( 160, wallY, game.collisionTypes.LEFT_WALL ); this.leftWall.createWall(); me.game.world.addChild(this.leftWall, 2); console.log("Creating Middle Wall"); this.middleWall = new game.Wall( me.game.viewport.width / 2 - 16, wallY, game.collisionTypes.MIDDLE_WALL ); this.middleWall.createWall(); me.game.world.addChild(this.middleWall, 2); console.log("Creating Right Wall"); this.rightWall = new game.Wall( me.game.viewport.width - 192, wallY, game.collisionTypes.RIGHT_WALL ); ... } Here's the code for the Wall 'class': game.Wall = me.Container.extend({ init: function (left, top, collisionType) { // A Wall is composed of three sections, each representing // a different character. this.PREFIXES = ["wall_L_","wall_M_","wall_R_"]; // Each Character, or wall section, is cut up into a grid of // four rows and columns. this.COLS = 4; this.ROWS = 4; this.PIECE_WIDTH = 16; this.PIECE_HEIGHT = 16; // The width of an entire row (and the container itself), the width of each piece (cell) // or column in a wall section * the number of columns per wall section // * the number of wall sections this.wallWidth = this.PIECE_WIDTH * this.COLS * this.PREFIXES.length; this.wallHeight = this.PIECE_HEIGHT * this.ROWS; this._super(me.Container, "init", [left, top, this.wallWidth, this.wallHeight]); this.vel = 0; this.collisionType = collisionType; }, createWall: function () { // generate the entire wall, left to right, section by section, column by column for (var j = 0; j < this.ROWS; j++) { for (var c = 0; c < this.PREFIXES.length; c++ ) { for (var i = 0; i < this.COLS; i++) { // The name of the image var wallPiece = this.PREFIXES[c] + j + i; // The x and y coords for the wall piece var x = c * this.COLS * this.PIECE_WIDTH + i * this.PIECE_WIDTH; var y = j * this.PIECE_HEIGHT; // Add the piece as a child of the wall container. this.addChild(me.pool.pull("wall_piece", x, y, wallPiece, this.collisionType)); console.log("wall.createWall: (" + x + ", " + y + "); img: " + wallPiece); } } } this.updateChildBounds(); this.createdWall = true; }, onActivateEvent: function () { }, onDeactivateEvent: function () { }, removeChildNow: function (child) { this._super(me.Container, "removeChildNow", [child]); this.updateChildBounds(); }, update: function (dt) { this._super(me.Container, "update", [dt]); this.updateChildBounds(); } }); and, the onCollision method from laser.js (i've defined custom collision types) onCollision: function (res, other) { if (other.body.collisionType === me.collision.types.ENEMY_OBJECT) { me.game.world.removeChild(this); game.playScreen.enemyManager.removeChild(other); return false; } if (other.body.collisionType === game.collisionTypes.LEFT_WALL) { me.game.world.removeChild(this); game.playScreen.leftWall.removeChild(other); return false; } if (other.body.collisionType === game.collisionTypes.MIDDLE_WALL) { me.game.world.removeChild(this); game.playScreen.middleWall.removeChild(other); return false; } if (other.body.collisionType === game.collisionTypes.RIGHT_WALL) { me.game.world.removeChild(this); game.playScreen.rightWall.removeChild(other); return false; } }
-
Collision works with single Sprite and the Map, but it doesn't with objects created with function createFromObjects. The callback function never displays the console.log() message. The sprites move through the tiles, never colliding with the map. I'm new to phaser3, so maybe I'm missing something. Here's the code: preload() { this.load.image('tiles', 'assets/levels_tileset.png'); this.load.tilemapTiledJSON('level1', 'assets/maps/map1.json'); this.load.spritesheet('player', 'assets/dude.png', {frameWidth: 32, frameHeight: 48}); this.load.spritesheet('enemies', 'assets/spritesheet_enemies.png', {frameWidth: 47, frameHeight: 47}); } create() { var map = this.make.tilemap({ key: 'level1' }); var tiles = map.addTilesetImage('levels_tileset', 'tiles'); this.layer = map.createDynamicLayer('blocks', tiles, 0, 0); this.layer.setCollisionByExclusion([-1]); this.player = this.physics.add.sprite(100, 450, 'player'); this.player.setBounce(0.2); this.player.setCollideWorldBounds(true); this.player.body.setGravityY(300); this.physics.add.collider(this.layer, this.player); this.right = true; this.enemies = this.physics.add.group(); this.enemies = map.createFromObjects('enemies_objects', 'enemy1', { key: 'enemies' }); this.enemies.forEach((child) => { if(child instanceof Phaser.GameObjects.Sprite) { child.setFrame(4); } }); this.physics.add.collider(this.enemies, this.layer, this.bounce, null, this); } update() { this.enemies.forEach((enemy) => { if(enemy instanceof Phaser.GameObjects.Sprite) { if(this.right === true) { enemy.x += 1; } else { enemy.x -= 1; } } }); } bounce() { console.log("Collision!"); if(this.right === true) { this.right = false; } else { this.right = true; } } How can I fix this?
-
I've got a tilemap created in Tiled and there is a platform with ladder on the map. How to make player stop when it tries to move from platform to group layer? Also how to make player collide with tiles pointed by green arrow when player approaches then from left, bot not collide when player approaches from right. Simply, is there `checkCollision` property for a tile?
-
Hello, I've modified a little one labs example (first game). I have 1 ground platform and all stars falling on it, and a player. Plus collisions between everything, even between stars themselves. Player initially is in the middle of the screen and stars. If I move to the right - stars are moving, hitting each one and all joining the line; so you hit 1 and move it, then 2'nd star joins, then 3'rd, 4'th and so on. That's correct, you get all stars in a line next to each other. The issue appears when you move to the left - I'm able to join only 2 stars - all other acts like physicsless and player/stars just go through them. So you get max 2 stars in a row. Is this an arcade/collisions bug? What can I do to make collisions always be the same and objects do not go through each other? If I comment out the internals of my function collideElem - results for different directions are still different. I use it for stopping the star after a collision. Here is my testing code which is runnable at labs.phaser.io: var config = { type: Phaser.AUTO, width: 800, height: 600, physics: { default: 'arcade', arcade: { gravity: { y: 300 }, debug: false } }, scene: { preload: preload, create: create, update: update } }; var player; var stars; var platforms; var cursors; var game = new Phaser.Game(config); function preload () { this.load.image('sky', 'src/games/firstgame/assets/sky.png'); this.load.image('ground', 'src/games/firstgame/assets/platform.png'); this.load.image('star', 'src/games/firstgame/assets/star.png'); this.load.spritesheet('dude', 'src/games/firstgame/assets/dude.png', { frameWidth: 32, frameHeight: 48 }); } function create () { this.add.image(400, 300, 'sky'); platforms = this.physics.add.staticGroup(); platforms.create(400, 568, 'ground').setScale(2).refreshBody(); player = this.physics.add.sprite(300, 450, 'dude'); player.setCollideWorldBounds(true); this.anims.create({ key: 'left', frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }), frameRate: 10, repeat: -1 }); this.anims.create({ key: 'turn', frames: [ { key: 'dude', frame: 4 } ], frameRate: 20 }); this.anims.create({ key: 'right', frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }), frameRate: 10, repeat: -1 }); cursors = this.input.keyboard.createCursorKeys(); stars = this.physics.add.group({ key: 'star', repeat: 11, setXY: { x: 12, y: 0, stepX: 70 } }); this.physics.add.collider(player, platforms); this.physics.add.collider(stars, platforms); this.physics.add.collider(player, stars, collideElem, null, this); this.physics.add.collider(stars, stars, collideElem, null, this); } function collideElem(obj1, obj2) { obj2.body.setVelocityX(0); obj2.body.setVelocityX(0); } function update () { if (cursors.left.isDown) { player.setVelocityX(-160); player.anims.play('left', true); } else if (cursors.right.isDown) { player.setVelocityX(160); player.anims.play('right', true); } else { player.setVelocityX(0); player.anims.play('turn'); } if (cursors.up.isDown && player.body.touching.down) { player.setVelocityY(-330); } }
-
See updates in below comments I made a collider: this normally works. But however this time it doesn't. There is a collider which lets the player colliding with (this) object. when I move the player on the object, the collideCB is triggered. But there is no collision. Even in debug mode for arcade physics, I can see the body. But they are not colliding, just overlapping. Anyone has an idea why? body: this.scene.physics.world.enable(this); this.setOrigin(0, 0); this.body.setSize(8, 8, false); this.body.setImmovable(true); this.body.allowGravity = false; colliding code: this.scene.physics.add.collider(this.scene.config.player, this, collideCB, () => { return this.getData('active'); }, this) (...) collideCB() { console.log('working') } Also, the debug information seems to clearly address both sprites, that should collide. but it does not collide and the callback is fired. ALl other collisions are working. (attached screenshot)
-
Hello, found a bug in the matter physics engine collision detector, I'm working with polygonal colliders. When an object collides with another and passes through it the "collision end" event doesn't trigger until de object is outside the real shape of the sprite (image size). I'm attaching a small video of it in which I'm logging the collision between the small vert of the triangle against the body of the other triangle, you can see how the "collision end" triggers when the vert enters and leave from the same side but not when it goes through it (until leaving the image size). Hope it helps fixing it! and if anyone knowns a workaround it would really help me. Regards. Edit: here's a small c9 demo (event trigger notification on console). https://ide.c9.io/mmolina01/phaser-matter-demo https://phaser-matter-demo-mmolina01.c9users.io/ collisions.mov
-
I have a sprite of a character moving and I'm trying to apply physics collide on it that when it hits a rock for example health is decreased. I managed to achieve collision but as rectangular shape of the image, what I want to achieve is the collision happens on the boundaries of the character itself. I used PhysicsEditor to generate the JSON file, but I'm still not sure how to use it to achieve pixel perfect collision. Any thoughts?
-
Hi there, today I started learning Phaser3 - I'm building Flappy Bid game. Unofrtunately I have problem with detecting of collision - it seems that overlap is not working for me and this.bird and this.pipes are never colliding according to it :(. I have tried several solutions but none seems to be working for me. I'm using phaser version from npm, because I'm working with React along for some UI stuff. Also I'm not sure if I can somehow refresh texture of all pipe elements after it is loaded? Also this.bird.body is returning undefined - I don't know why is this. I think it should return Arcadic Physics? import Phaser from 'phaser'; import bird from '../../assets/bird.png'; import pipe from '../../assets/pipe.png'; class GameScene extends Phaser.Scene { constructor(test) { super({ key: 'GameScene', physics: { arcade: { gravity: { y: 0 }, debug: true } }, }); } preload() { this.textures.addBase64('bird', bird); this.textures.addBase64('pipe', pipe); } create() { // updating textures this.textures.on('onload', () => { this.bird.setTexture('bird'); }); // bird definition this.bird = this.physics.add.image(100, 245, 'bird') .setActive(true) .setVelocity(0, 0) .setGravity(0, 1000) this.physics.world.enable(this.bird) // obstacles definition this.pipes = this.add.group(); this.physics.world.enable(this.pipes) this.keys = { jump: this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP) } this.timedEvent = setInterval(() => { this.addPipeColumn(); }, 2000); this.addPipeColumn(); } update() { if (this.bird.y < 0 || this.bird.y > 800) { this.gameOver(); } if (this.keys.jump.isDown) { this.jump(); } this.physics.overlap(this.bird, this.pipes, this.gameOver, null, this) } gameOver() { clearInterval(this.timedEvent); this.scene.restart(); } jump() { this.bird.body.velocity.y = -350; } addPipe(x, y) { const pipe = this.physics.add.image(x, y, 'pipe') .setActive() .setVelocity(-200, 0) .setGravity(0); pipe.checkWorldBounds = true; pipe.outOfBoundsKill = true; this.pipes.create(pipe); } addPipeColumn() { const hole = Math.floor(Math.random() * 5) + 1; for (let i = 0; i < 12; i++) { if (i !== hole && i !== hole + 1) { this.addPipe(800, i * 60 + 10); } } } } export default GameScene I'm also adding React code where I mount Game: import React, { Component } from 'react'; import Phaser from 'phaser'; import GameScene from './scenes/GameScene' class Game extends Component { componentDidMount() { this.createGame(); } createGame() { const config = { type: Phaser.AUTO, width: 800, height: 600, parent: 'Game', backgroundColor: '#71c5cf', // comment out general physics // physics: { // default: 'arcade', // arcade: { // gravity: { y: 100 } // } // }, scene: [ GameScene ] }; // creating game new Phaser.Game(config); } render() { return ( <div id="Game"></div> ); } } export default Game;
-
Hi there, I'm playing around with the v3 API and wondered how to collide with a layer of a tilemap. Here is what I've already tried: 1) Get tiles data (there is probably a better way / API helper for that like forEachTile) and then use setCollision. let tilesData = (this.platformLayer.data.gameObject.map.tiles) this.map.setCollision(tilesData, true, false, this.platformLayer) 2) Do the opposite by excluding an empty array. this.map.setCollisionByExclusion([], true, false, this.platformLayer) 3) API v2 style. this.physics.arcade.collide(this.player, this.platformLayer); Here is my game config, if someone have the time to spot what I'm doing wrong. Thanks! let config = { type: Phaser.AUTO, parent: 'content', width: 800, height: 600, pixelArt: true, backgroundColor: '#2d2d2d', physics: { default: 'impact', impact: { setBounds: true, debug: true }, }, scene: [ Boot, Preload, TileMapTest ] } let game = new Phaser.Game(config) And here is my Scene /* globals __DEV__ */ class TileMapTest extends Phaser.Scene { constructor () { super({ key: 'TileMapTest' }) if (__DEV__) { console.log('TileMapTest scene created.') } this.map = null this.player = null this.cursors = null this.rockLayer = null this.waterLayer = null this.platformLayer = null this.stuffLayer = null } preload () { // Hero this.load.image('hero', './assets/sprites/hero.png') // Tilemap this.load.image('kenny_platformer_64x64', './assets/tilemaps/tiles/kenny_platformer_64x64.png') this.load.tilemapJSON('multiple-layers-map', './assets/tilemaps/maps/multiple-layers.json') } create () { if (__DEV__) { console.log('TileMapTest scene entered.') } this.createTileMapLayers() this.createPlayer() this.cameras.main.startFollow(this.player) this.cameras.main.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels) this.physics.world.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels) // ---> @todo collide with platformLayer } update (time, delta) { this.updatePlayer(time, delta) } createPlayer () { this.player = this.physics.add.sprite(200, 200, 'hero', 4).setOrigin(0, 0.15) this.player.setActive() this.player.setMaxVelocity(500) this.player.setFriction(1000, 100) this.player.body.accelGround = 1200 this.player.body.accelAir = 600 this.player.body.jumpSpeed = 500 // this.player.body.collideWorldBounds = true this.cursors = this.input.keyboard.createCursorKeys() } createTileMapLayers () { this.map = this.make.tilemap({ key: 'multiple-layers-map' }) let tiles = this.map.addTilesetImage('kenny_platformer_64x64') this.rockLayer = this.map.createStaticLayer('Rock Layer', tiles, 0, 0) this.waterLayer = this.map.createStaticLayer('Water Layer', tiles, 0, 0) this.platformLayer = this.map.createStaticLayer('Platform Layer', tiles, 0, 0) this.stuffLayer = this.map.createStaticLayer('Stuff Layer', tiles, 0, 0) } updatePlayer (time, delta) { let accel = this.player.body.standing ? this.player.body.accelGround : this.player.body.accelAir if (this.cursors.left.isDown) { this.player.setAccelerationX(-accel) } else if (this.cursors.right.isDown) { this.player.setAccelerationX(accel) } else { this.player.setAccelerationX(0) } // Jump if (this.cursors.up.isDown && this.player.body.standing) { this.player.setVelocityY(-this.player.body.jumpSpeed) } } } export default TileMapTest
-
Hello, The answers to my questions may seem evident, please consider I'm a complete beginner to HTML and JS Phaser coding. I am having two problems with my code. The first is that renderTexture doesn't seem to work. I am trying to make a trail of my player, like the "trail" example on labs.phaser.io. I actually copied the code needed, but it does not work. Here is the line causing the problem: rt = this.make.renderTexture({ x: 0, y: 0, width: 800, height: 800 }).setOrigin(0, 0); in the create function. And here is what the console says: Uncaught TypeError: this.make.renderTexture is not a function at Scene.create ((index):301) at SceneManager.create (phaser.js:51412) at SceneManager.loadComplete (phaser.js:51329) at LoaderPlugin.emit (phaser.js:2622) at LoaderPlugin.processComplete (phaser.js:111210) at LoaderPlugin.removeFromQueue (phaser.js:111190) at LoaderPlugin.processUpdate (phaser.js:111171) at Image.data.onload (phaser.js:8947) _____________ The second issue affects the collision boxes of my obstacles. Those are static sprites, and the physics are "MatterJS". I have defined the shape of the hitboxes in PhysicsEditor, and have done exactly like in their tutorial to link the JSON to the sprites, but it doesn't work: the collision is not only triggered when the player enters the parts in the shape, but also in the rest of the rectangle that should not be considered. Furthermore, all physical properties I've set in the editor don't work. Then, I tried to do all of it without physicsEditor: I added required setters to do the work. While the physical properties are now correct, the hitboxes are still the whole rectangles instead of the chosen parts. Here is the code: //example var ob12 = this.matter.add.sprite(800-211, -6353, 'ob12').setStatic(true).setSensor(true).setFriction(0,0,0).setInteractive(new Phaser.Geom.Polygon([ [ { "x":132, "y":291 }, { "x":337, "y":498 }, { "x":423, "y":2 } ], [ { "x":50, "y":789 }, { "x":239, "y":979 }, { "x":337, "y":498 } ], [ { "x":0, "y":1220 }, { "x":423, "y":1639 }, { "x":239, "y":979 } ], [ { "x":239, "y":979 }, { "x":423, "y":1639 }, { "x":337, "y":498 } ], [ { "x":337, "y":498 }, { "x":423, "y":1639 }, { "x":423, "y":2 } ] ]), Phaser.Geom.Polygon.Contains); Thank you, Vainly
- 9 replies
-
- phaser 3
- rendertexture
- (and 5 more)
-
Hello! I've noticed, that if I modify exact tile's collisions with tile.setCollision(false, false, true, false) - it also disables neighbor tiles collisions (left-right directions). A screenshot is attached. Red arrow shows a modified tile, blue arrow shows a tile which's left-right collisions have disappeared. Lab's modified example that you can copy-paste into https://labs.phaser.io/edit.html?src=src/game objects/tilemap/collision/tile callbacks.js : var config = { type: Phaser.WEBGL, width: 800, height: 576, parent: 'phaser-example', physics: { default: 'arcade', arcade: { gravity: { y: 300 } } }, scene: { preload: preload, create: create, update: update } }; var game = new Phaser.Game(config); var map; var cursors; var debugGraphics; var text; var player; var groundLayer; function preload () { this.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); this.load.tilemapTiledJSON('map', 'assets/tilemaps/maps/tile-collision-test.json'); this.load.image('player', 'assets/sprites/phaser-dude.png'); } function create () { map = this.make.tilemap({ key: 'map' }); var groundTiles = map.addTilesetImage('ground_1x1'); map.createDynamicLayer('Background Layer', groundTiles, 0, 0); groundLayer = map.createDynamicLayer('Ground Layer', groundTiles, 0, 0); groundLayer.layer.data[8][8].index = 11; groundLayer.layer.data[8][9].index = 1; groundLayer.setCollisionBetween(1, 10); // This breaks the collisions with the neighbor tiles groundLayer.layer.data[8][8].setCollision(false, false, true, false); player = this.physics.add.sprite(80, 70, 'player').setBounce(0.1); // We want the player to physically collide with the ground this.physics.add.collider(player, groundLayer); this.cameras.main.setBounds(0, 0, map.widthInPixels, map.heightInPixels); this.cameras.main.startFollow(player); cursors = this.input.keyboard.createCursorKeys(); text = this.add.text(16, 16, 'Arrow keys to move. Space to jump', { fontSize: '20px', fill: '#ffffff' }); text.setScrollFactor(0); text.setText('Arrow keys to move. Space to jump'); } function update (time, delta) { // Horizontal movement player.body.setVelocityX(0); if (cursors.left.isDown) { player.body.setVelocityX(-200); } else if (cursors.right.isDown) { player.body.setVelocityX(200); } // Jumping if ((cursors.space.isDown || cursors.up.isDown) && player.body.onFloor()) { player.body.setVelocityY(-300); } } Here important is line 48: groundLayer.layer.data[8][8].setCollision(false, false, true, false); If you comment it out - everything is OK - you can walk through red arrow's tile and blue tile's collisions works fine. If you run it as is - you can walk through red arrow's tile and through neighbor blue tiles too - this is wrong. How this can be fixed? Thanks!