@amorphine

Текст, связанный с координатами спрайта отрисовывается с запозданием в Phaser.JS. По какой причине?

Унаследуем спрайт со своими свойствами
import 'phaser';

/**
 * Represents a unit
 */
class Ship extends Phaser.Sprite{
    constructor(game, x, y, color, radius, frame) {
        let bmd, style;

        //Bitmap data
        bmd = game.make.bitmapData(radius*2, radius*2);
        bmd.circle(radius, radius, radius, color);
        super(game, x, y, bmd, frame);

        //add the sprite to the stage
        game.add.existing(this);

        //text data
        style = { font: "9px Arial", fill: "#fff", wordWrap: true, wordWrapWidth: this.width, align: "center" };
        this.text = game.add.text(0, 0, "B", style);
        this.text.anchor.set(0.5, 0.3);

        this.updateTextPos ();
    }

    /**
     * Update text coords
     */
    updateTextPos ()  {
        this.text.x = Math.floor(this.x + this.width/2);
        this.text.y = Math.floor(this.y + this.height/2);
    }
}
export default Ship;


Портянка практически стандартного кода из любого туториала, ничего особенного.
import 'p2';
import 'pixi';
import 'phaser';
import Ship from './ships/ship';

let game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.WEBGL, '', { preload: preload, create: create, update: update });

function preload() {
    game.load.image('background', '/assets/images/background.jpg');
}


let player,
    cursors;

function create() {
    game.add.tileSprite(0, 0, 2884, 2064, 'background');
    game.world.setBounds(0, 0, 2884, 2064);

    game.physics.startSystem(Phaser.Physics.P2JS);

    player = new Ship(game, game.world.centerX, game.world.centerY,  'rgba(255,0,0,0.8)', 8);

    game.physics.enable(player, Phaser.Physics.ARCADE);

    cursors = game.input.keyboard.createCursorKeys();

    game.camera.follow(player);
}

function update() {

    //  only move when you click
    if (game.input.mousePointer.isDown)
    {
        //  400 is the speed it will move towards the mouse
        game.physics.arcade.moveToPointer(player, 200);

        //  if it's overlapping the mouse, don't move any more
        if (Phaser.Rectangle.contains(player.body, game.input.x, game.input.y))
        {
            player.body.velocity.setTo(0, 0);
        }
    }
    else
    {
        player.body.velocity.setTo(0, 0);
    }

    //redraw text
    player.updateTextPos();

}


Кружок с надписью B нормально передвигается за курсором, здесь вопросов нет.
Но надпись на кружке на скорости перерисовывается с запозданием, смещаясь к краю.
В момент остановки она возвращается на середину, как и положено.
В чем может быть причина? Может, есть способы по-другому добавить текстовую информацию к спрайту?

Без движения:
2d9f73d2e077475599d967be3fbd2105.png

В движении:
e54d09164e9b479ca4cd26624d0d9c6f.png

Делал по туториалу
Техника та - же. На каждую отрисовку отцентровываем текст на спрайте. Код проходит через babel. Может ли проблема быть следствием оверхеда из-за генерируемого ES5-кода?
  • Вопрос задан
  • 295 просмотров
Пригласить эксперта
Ответы на вопрос 1
Я хз из-за чего проблема, но лично я такие вещи, например хелсбары над юнитами делал с помощью addChild().

Т.е. просто кораблю делаешь this.addChild(text), и он будет намертво привинчен всегда к кораблю.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы