es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿Cómo agrego un objeto al lado de un objeto en movimiento en Phaser?

En el fragmento de código a continuación, coloco dos cuadrados rojos uno al lado del otro. Puede ver que no hay espacio entre ellos.

Si intento hacer lo mismo con objetos en movimiento, hay una ligera separación. ¿Cuál es la manera correcta de hacer esto?

Imagen:

View post on imgur.com

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.min.js"></script>
  </head>
  <body>
    <script>
    var config = {
      type: Phaser.AUTO,
      width: 800,
      height: 600,
      physics: { default: 'arcade' },
      scene: { create: create, update: update },
    };

var game = new Phaser.Game(config);
var red, red2, yellow, yellow2;
const velocity = -300;

function create() {
  red = this.add.rectangle(400, 200, 100, 100, 0xff0000).setOrigin(0, 0);
  red2 = this.add.rectangle(red.x + 100, 250, 100, 100, 0xff6666).setOrigin(0, 0);

  yellow = this.add.rectangle(400, 400, 100, 100, 0xffff00).setOrigin(0, 0);
  this.physics.add.existing(yellow);
  yellow.body.velocity.x = velocity;
}

function update() {
  if (yellow.x < 200 && !yellow2) {
    yellow2 = this.add.rectangle(yellow.x + 100, 450, 100, 100, 0xffff66).setOrigin(0, 0);
    this.physics.add.existing(yellow2);
    yellow2.body.velocity.x = velocity;
  }
  if (yellow.x < -200) {
    this.scene.restart();
    yellow2 = undefined;
  }
}
</script>
</body>
</html>
Tags:  

Answer

  1. Avatar for davy.ai

    Para eliminar la brecha entre los dos cuadrados amarillos móviles, debemos asegurarnos de que sus posiciones estén alineadas entre sí. Esto se puede lograr estableciendo su posición x mediante la posición x del cuadrado anterior más su ancho, en lugar de un valor fijo de 100.

    Aquí hay una versión actualizada de la función update que implementa esta solución:

    function update() {
      if (yellow.x < 200 && !yellow2) {
        yellow2 = this.add.rectangle(yellow.x + yellow.width, 450, 100, 100, 0xffff66).setOrigin(0, 0);
        this.physics.add.existing(yellow2);
        yellow2.body.velocity.x = velocity;
      }
      if (yellow.x < -200) {
        this.scene.restart();
        yellow2 = undefined;
      }
    }
    

    Esto garantizará que los dos cuadrados amarillos siempre estén posicionados uno al lado del otro, sin brecha entre ellos.

Comments are closed.