Phaser Custom Process Collision Function
by incutonez
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.85.1/phaser.min.js"></script>
TypeScript
const Velocity = 80;
let direction;
class Example extends Phaser.Scene {
constructor() {
super();
}
preload() {
this.load.image('tile', 'https://i.imgur.com/TttprwB.png');
this.load.image('player', 'https://i.imgur.com/zJVFvQN.png')
}
create() {
const tile = this.tile = this.physics.add.image(128, 64, 'tile')
tile.setImmovable(true);
const player = this.player = this.physics.add.image(128, 192, 'player');
player.setMaxVelocity(Velocity);
const triangle = new Phaser.Geom.Triangle(tile.getTopLeft().x, tile.getTopLeft().y, tile.getTopRight().x, tile.getTopRight().y, tile.getBottomRight().x, tile.getBottomRight().y);
const cursor = this.cursor = this.input.keyboard.createCursorKeys();
this.physics.add.collider(tile, [player], (a, b) => {
console.log('here')
}, (a, b) => {
const rect = new Phaser.Geom.Rectangle(
b.getBounds().x,
b.getBounds().y,
64,
64
);
const intersecting = Phaser.Geom.Intersects.RectangleToTriangle(rect, triangle);
console.log(intersecting)
if (intersecting) {
if (cursor.up.isDown) {
direction = 'up';
}
else if (cursor.down.isDown) {
direction = 'down';
}
else if (cursor.left.isDown) {
direction = 'left';
}
else if (cursor.right.isDown) {
direction = 'right';
}
}
return intersecting;
});
}
update() {
const {
cursor,
player
} = this;
let velocityX = 0;
let velocityY = 0;
console.log(direction);
if (cursor.left.isDown && direction !== 'left') {
velocityX = -Velocity;
/* this.physics.velocityFromRotation(0, velocityX, player.body.velocity) */;
} else if (cursor.right.isDown && direction !== 'right') {
velocityX = Velocity;
/* this.physics.velocityFromRotation(0, velocityX, player.body.velocity) */;
}
if...