How to charachter stand only center of tile not our site of tile - phaser-framework

My code is here please look it. I have try my option but stuck in this.
https://www.codepile.net/pile/7mPpA9m0
What i do and please share me best solution. I'm stuck from last 2 weeks. in this problem please help me

As mention in a previews comment (I couldn't answer because the question was closed), the problem is the bounding-box of the physics objects.
It could be the player or the platform, depending on the images.
To know for sure turn on the debug information(debug: true) in the config of the Phaser Game Object. (a nice demo can be found here: https://phaser.io/examples/v3/view/physics/arcade/custom-debug-colors)
And than adjust the size of the bounding box. _(a nice demo can be found here: https://phaser.io/examples/v3/view/physics/arcade/smaller-bounding-box)
I here you can see what I mean in action.
The red and white player would have the same bounding box, but I made the box of the white player smaller with the function setSize and adjusted the position of the bounding box with the function setOffset.
Here a working Demo:
var config = {
type: Phaser.AUTO,
width: 536,
height: 183,
scene: {
create: create
},
physics: {
default: 'arcade',
arcade: {
gravity:{y:100},
//show debug information
debug: true
}
},
banner: false
};
function create () {
// JUST FOR DEMO START
let graphics = this.make.graphics();
graphics.fillStyle(0xffffff);
graphics.fillRect(10,5,10,25);
graphics.generateTexture('player', 30, 30);
// JUST FOR DEMO END
let platform = this.add.rectangle(150, 120, 100, 20, 0x00ff00)
.setOrigin(0, 1);
this.physics.add.existing(platform)
.body
.setImmovable(true)
.setAllowGravity(false);
let player = this.add.image(136, 50, 'player')
.setOrigin(.5, 1)
.setTint(0xff0000);
this.physics.add.existing(player);
let player2 = this.add.image(136, 50, 'player')
.setOrigin(.5, 1);
this.physics.add.existing(player2)
.body
// CHANGE SIZE OFF PHYSICS BOX
.setSize(14, 25, false)
.setOffset(8, 5)
.setAllowGravity(false)
.setVelocityY(10)
this.physics.add.collider(player, platform);
this.physics.add.collider(player2, platform);
}
var game = new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js">
</script>
Depending on, if you player's or your platforms bounding-box is to big you will have to adjust it, or make images, that have less transparent borders.

Related

How to make a tooltip appear when hovering mouse over a Phaser.GameObject.Image?

In my Phaser 3 game I'm using Phaser.GameObjects.Image 's as things that a user can click on. When a user's mouse hovers over an image I would like a tooltip with text to fade in and appear. When the mouse moves off the image, I'd like the tooltip to disappear.
How can I implement this behavior in Phaser? I'm new to Phaser and I don't see a ToolTip class in the framework.
You could:
use the pointer events for detecting, that the pointer is over an object
and animate/tween the alpha property on the over event
you can alter the speed with the tween duration
and hide the toolTip on the out event
Here the docs to the Input events: https://photonstorm.github.io/phaser3-docs/Phaser.Input.Events.html
Here a mini example:
var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
width: 800,
height: 600,
scene: {
create: create
}
};
var game = new Phaser.Game(config);
var toolTip;
var toolTipText;
function create ()
{
let objectWithToolTip = this.add.rectangle( 100, 100, 100, 100, 0xffffff).setInteractive();
toolTip = this.add.rectangle( 0, 0, 250, 50, 0xff0000).setOrigin(0);
toolTipText = this.add.text( 0, 0, 'This is a white rectangle', { fontFamily: 'Arial', color: '#000' }).setOrigin(0);
toolTip.alpha = 0;
this.input.setPollOnMove();
this.input.on('gameobjectover', function (pointer, gameObject) {
this.tweens.add({
targets: [toolTip, toolTipText],
alpha: {from:0, to:1},
repeat: 0,
duration: 500
});
}, this);
this.input.on('gameobjectout', function (pointer, gameObject) {
toolTip.alpha = 0;
toolTipText.alpha = 0;
});
objectWithToolTip.on('pointermove', function (pointer) {
toolTip.x = pointer.x;
toolTip.y = pointer.y;
toolTipText.x = pointer.x + 5;
toolTipText.y = pointer.y + 5;
});
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.min.js"></script>
Info: if you want to dig deeper into the phaser events you can checkout some examples on the offical home page: https://phaser.io/examples/v3/category/input/mouse are really good, and explore may use cases.
Extra Info: If you don't want to re-invent the wheel, there are several plugins, that can be loaded into phaser(that add special functionality to phaser).
It is always good to check this page(https://phaserplugins.com/), before implementing so common feature/function. There is even on specially for tooltips https://github.com/netgfx/Phaser-tooltip

How to repeat Paths in Free Drawing?

Please look at
https://stackblitz.com/edit/js-wxidql
Here is my code.
import { fabric } from "fabric";
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
let offsetPath = new fabric.Path();
let offsetLeft = mousePath.left + 60;
let offsetTop = mousePath.top + 60;
offsetPath.setOptions({
path: mousePath.path,
left: offsetLeft,
top: offsetTop,
width: mousePath.width,
height: mousePath.height,
fill: '',
stroke: 'black'
});
canvas.add(offsetPath);
canvas.requestRenderAll();
});
Here is an resulting image of my drawing session.
I drew the happy face in the top left corner of the canvas with my mouse.
The offset image was added by my code.
How can I change my code to make the offset drawing look like the one drawn with my mouse?
Edit: from https://github.com/fabricjs/fabric.js/wiki/When-to-call-setCoords
I tried using
offsetDraw.setCoords();
but I was unable to find a way to make it work.
Edit: What I have presented here is a minimized example. I am working on an larger project where I save each path drawn by the user. Later I recreate those paths in an animation like sequence.
Edit: I made some changes to my code in a effort to understand fabricjs.
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
let offsetPath = new fabric.Path();
let offsetLeft = mousePath.left + 60;
let offsetTop = mousePath.top + 60;
offsetPath.setOptions({
path: mousePath.path,
//left: offsetLeft,
//top: offsetTop,
width: mousePath.width,
height: mousePath.height,
fill: '',
stroke: 'black'
});
canvas.add(offsetPath);
canvas.requestRenderAll();
console.log("mousePath left " + mousePath.left + " top " + mousePath.top);
console.log("offsetPath left " + offsetPath.left + " top " + offsetPath.top);
});
In that code, I commented out the setting of the left and top properties of the offsetPath and added console.log lines. I drew a circle in the top left corner of the canvas with my mouse. The resulting image was the following.
The following was printed in the console.
mousePath left 7.488148148148148 top 10.5
offsetPath left -0.5 top -0.5
I don't understand the results. Why was the offset circle rendered in that position?
Edit: I drew another test with my mouse.
It seems that the code repeats the paths of concentric circles rather well. But, the vertical lines are moved out of their correct position. Their displacements increase as the distance from the center increases. Why?
I found a solution for my own question. But, if someone has a better one, then please post it. Look at
https://stackblitz.com/edit/js-ncxvpg
The following is the code.
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
mousePath.clone(clone => {
clone.setOptions({
left: mousePath.left + 100,
top: mousePath.top + 100
});
canvas.add(clone);
});
});
If someone has an explaination as to why my original code didn't work, then please post it.
thanks for sharing your comments on my question. I am facing a similar issue, just that if I click anywhere on the Canvas the first time. Then the offset issue vanishes. This happens for any object that I programmatically insert into the canvas.
In my case, I suspect that the canvas.pointer is having some offset of the current mouse position. However, when I click and add one very small path of 1pixel, then the pointer offset gets corrected. After this, all subsequent paths or objects created programatically are shown at the correct positions.

How do I adjust Player's physical bounds?

Object Boundary
I'm a new Phaser developer, in the beginning stages of my first game. My problem is, when my player hits the ground, the bounding box defining his bounds is way bigger than he is (see pic). So in the example shown, the player will bounce when the borders touch, not his feet.
In action
Physics Matter
Do I have to change from ARCADE physics to a more robust physics engine, in order to accomplish my goal?
Code
There's really not much to show, but here is what I have:
/// <reference path="../defs/phaser.d.ts" />
class MainGame extends Phaser.Scene {
constructor() {
super("MainGame");
}
preload() {
this.load.image("bg1", "assets/bg-level1.png");
this.load.image('ground', 'assets/platform.png');
this.load.spritesheet('dude', 'assets/final-jump.png', {
frameWidth: 118,
frameHeight: 118
});
}
create() {
this.setupBackground();
this.setupPlayer();
this.add.text(0, 0, 'Use Cursors to scroll camera.\nQ / E to zoom in and out', {
font: '18px Courier',
fill: 'black'
});
this.physics.add.collider(this.player, this.platforms);
}
update() {
// Set Player Animations
this.setPlayerAnimation();
if (this.player.body.onFloor()) {
console.log("FLOOR");
this.player.body.setAccelerationX(31);
this.player.body.setAccelerationY(31);
}
}
//---------------------------------
// CREATE RELATED FUNCTIONS
//---------------------------------
setupBackground() {
this.background = this.add.image(0, 0, "bg1");
this.background.setOrigin(0, 0);
//this.background.setInteractive();
this.background.setAlpha(.2, .2, .2, .2);
// The platforms group contains the ground and the 2 ledges we can jump on
this.platforms = this.physics.add.staticGroup();
// Here we create the ground.
// Scale it to fit the width of the game (the original sprite is 400x32 in size)
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
}
setupPlayer() {
this.player = this.physics.add.sprite(100, 283, 'dude');
console.log(this.player.body.touching.down);
this.player.setVelocity(200, 100).setBounce(.8, .8).setCollideWorldBounds(true);
// Re-Size Player Size
this.player.setDisplaySize(220, 210);
// Collision Handler
this.physics.add.overlap(this.player, this.platforms, this.showJump, null, this);
// ANIMATIONS
this.anims.create({
key: 'jump-up',
frames: this.anims.generateFrameNumbers('dude', {
start: 1,
end: 2
}),
frameRate: 5,
repeat: 1
});
this.anims.create({
key: 'falling',
frames: this.anims.generateFrameNumbers('dude', {
start: 0,
end: 1
}),
frameRate: 5,
repeat: 1
});
this.anims.create({
key: 'onGround',
frames: this.anims.generateFrameNumbers('dude', {
start: 4,
end: 4
}),
frameRate: 24,
repeat: 1
});
}
showJump() {
this.player.anims.play('jump-up', true);
}
//---------------------------------
// UPDATE RELATED FUNCTIONS
//---------------------------------
setPlayerAnimation() {
//this.player.anims.play('jump-up', true);
if (this.player.body.deltaY() > 0 && this.player.body.onFloor()) {
this.player.anims.play('falling', true);
}
}
}
Oh, Yeah...
I am very impressed with the functionality of the local documentation package I downloaded and installed, however, I'm confused on where to begin looking for something. For instance, let's say I am struggling with making my player jump and play an animation when in the air, and change back when he hits the ground. Given that information, how do I find the correct class or function I need???
You do not have to change from arcade physics. Try something like this:
// Change the size of the bounding box.
this.player.setSize(32, 32);
// Change the location of the bounding box.
this.player.setOffset(0, 28);
// If that doesn't work, try this instead:
// this.player.body.setOffset(0, 28);
Obviously you need to adjust the width/height and offsets for your scenario.
References:
Sprite setSize method
Sprite setOffset method
Body setOffset method

Pixi.js How should HP write?

How should HP write?
Because HP will decrease, but I found that he will deform.
Each time container.hpStatus.width- = 1; HP's icon will be distorted, especially HP = 0 is most obvious.
enter image description here
You Can Look My Codepen.
app.ticker.add((delta) => {
if (container.hpStatus.width > 0) {
container.hpStatus.width -= 1;
} else {
container.hpStatus.width = 450;
}
});
How can i make sure he doesn't deform?
The hp bar is getting distorted because you are decreasing width of "container.hpStatus" which is Geometry object which is itself a Container:
https://pixijs.download/dev/docs/PIXI.Graphics.html#Graphics
And as you see in docs of the "width" property: https://pixijs.download/dev/docs/PIXI.Container.html#width
width number
The width of the Container, setting this will actually modify the scale to achieve the value set
It means that changing "width" scales whole container ("container.hpStatus").
To draw such hp bar without "distortion" you can do it by drawing hp bar on each "tick" (each frame).
Plaese check following code - is your example but modified. Most important parts are "createHpBar" function and modified "main loop" (ticker).
(i also added some comments so you can understand better)
and here is updated codepen: https://codepen.io/domis86/pen/poJrKdq
const app = new PIXI.Application({
view: document.getElementById('main'),
width: 900,
height: 900,
antialias: true,
transparent: false,
backgroundColor: 0x00CC99,
});
// See: https://pixijs.download/dev/docs/PIXI.Ticker.html
let ticker = PIXI.Ticker.shared;
ticker.autoStart = false;
const container = new PIXI.Container();
app.stage.addChild(container);
function createHpBar(currentHp, maxHp, color) {
let hpBar = new PIXI.Graphics();
hpBar.beginFill(color);
let hpPortion = currentHp / maxHp;
hpBar.drawPolygon([
50, 80,
50 + (400 * hpPortion), 80,
32 + (400 * hpPortion), 150,
32, 150,
]);
hpBar.endFill();
return hpBar;
}
// Create black hp bar (the one behind the red one) and add it to our container:
let blackHpBar = createHpBar(450, 450, 0x000000);
container.addChild(blackHpBar);
container.x = 100;
container.y = 200;
let renderer = app.renderer;
// Starting amount of hp:
var currentHp = 450;
ticker.add((delta) => {
// create red hp bar which is a polygon with vertices calculated using "currentHp" amount:
let redHpBar = createHpBar(currentHp, 450, 0xFF0000);
// add red hp bar to container:
container.addChild(redHpBar);
// render our stage (render all objects from containers added to stage)
// see https://pixijs.download/dev/docs/PIXI.Ticker.html#.shared
renderer.render(app.stage);
// Remove red hp bar from our container:
// We do this because on next tick (aka: next frame) we will create new redHpBar with "createHpBar" (as you see above)
container.removeChild(redHpBar);
// Update current hp amount:
if (currentHp > 0) {
currentHp -= 1;
} else {
currentHp = 450;
}
});
// start rendering loop:
ticker.start();

Phaser 3. Change dimensions of the game during runtime

Hi please help me to find out how trully responsive game can be created with Phaser3.
Respnsiveness is critical because game (representation layer of Blockly workspace) should be able to be exapanded to larger portion on screen and shrinked back many times during the session.
The question is How I can change dimentions of the game in runtime?
--- edited ---
It turns out there is pure css solution, canvas can be ajusted with css zoom property. In browser works well (no noticeable effect on performance), in cordova app (android) works too.
Here is Richard Davey's answer if css zoom can break things:
I've never actually tried it to be honest. Give it a go and see what
happens! It might break input, or it may carry on working. That (and
possibly the Scale Manager) are the only things it would break,
though, nothing else is likely to care much.
// is size of html element size that needed to fit
let props = { w: 1195, h: 612, elementId: 'myGame' };
// need to know game fixed size
let gameW = 1000, gameH = 750;
// detect zoom ratio from width or height
let isScaleWidth = gameW / gameH > props.w / props.h ? true : false;
// find zoom ratio
let zoom = isScaleWidth ? props.w / gameW : props.h / gameH;
// get DOM element, props.elementId is parent prop from Phaser game config
let el = document.getElementById(props.elementId);
// set css zoom of canvas element
el.style.zoom = zoom;
Resize the renderer as you're doing, but you also need to update the world bounds, as well as possibly the camera's bounds.
// the x,y, width and height of the games world
// the true, true, true, true, is setting which side of the world bounding box
// to check for collisions
this.physics.world.setBounds(x, y, width, height, true, true, true, true);
// setting the camera bound will set where the camera can scroll to
// I use the 'main' camera here fro simplicity, use whichever camera you use
this.cameras.main.setBounds(0, 0, width, height);
and that's how you can set the world boundary dynamically.
window.addEventListener('resize', () => {
game.resize(window.innerWidth, window.innerHeight);
});
There is some builtin support for resizing that can be configured in the Game Config. Check out the ScaleManager options. You have a number of options you can specify in the scale property, based on your needs.
I ended up using the following:
var config = {
type: Phaser.AUTO,
parent: 'game',
width: 1280, // initial width that determines the scaled size
height: 690,
scale: {
mode: Phaser.Scale.WIDTH_CONTROLS_HEIGHT ,
autoCenter: Phaser.Scale.CENTER_BOTH
},
physics: {
default: 'arcade',
arcade: {
gravity: {y: 0, x: 0},
debug: true
}
},
scene: {
key: 'main',
preload: preload,
create: this.create,
update: this.update
},
banner: false,
};
Just in case anybody else still has this problem, I found that just resizing the game didn't work for me and physics didn't do anything in my case.
To get it to work I needed to resize the game and also the scene's viewport (you can get the scene via the scenemanager which is a property of the game):
game.resize(width,height)
scene.cameras.main.setViewport(0,0,width,height)
For Phaser 3 the resize of the game now live inside the scale like this:
window.addEventListener('resize', () => {
game.scale.resize(window.innerWidth, window.innerHeight);
});
But if you need the entire game scale up and down only need this config:
const gameConfig: Phaser.Types.Core.GameConfig = {
...
scale: {
mode: Phaser.Scale.WIDTH_CONTROLS_HEIGHT,
},
...
};
export const game = new Phaser.Game(gameConfig);
Take a look at this article.
It explains how to dynamically resize the canvas while maintaining game ratio.
Note: All the code below is from the link above. I did not right any of this, it is sourced from the article linked above, but I am posting it here in case the link breaks in the future.
It uses CSS to center the canvas:
canvas{
display:block;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
It listens to the window 'resize' event and calls a function to resize the game.
Listening to the event:
window.onload = function(){
var gameConfig = {
//config here
};
var game = new Phaser.Game(gameConfig);
resize();
window.addEventListener("resize", resize, false);
}
Resizing the game:
function resize() {
var canvas = document.querySelector("canvas");
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var windowRatio = windowWidth / windowHeight;
var gameRatio = game.config.width / game.config.height;
if(windowRatio < gameRatio){
canvas.style.width = windowWidth + "px";
canvas.style.height = (windowWidth / gameRatio) + "px";
}
else{
canvas.style.width = (windowHeight * gameRatio) + "px";
canvas.style.height = windowHeight + "px";
}
}
I have used and modified this code in my phaser 3 project and it works great.
If you want to see other ways to resize dynamically check here
Put this in your create function:
const resize = ()=>{
game.scale.resize(window.innerWidth, window.innerHeight)
}
window.addEventListener("resize", resize, false);
Important! Make sure you have phaser 3.16+
Or else this won't work!!!
Use the game.resize function:
// when the page is loaded, create our game instance
window.onload = () => {
var game = new Game(config);
game.resize(400,700);
};
Note this only changes the canvas size, nothing else.

Resources