(JavaScript) 如何在移相器 3 中将图像定义为变量

(JavaScript) How to define images as a variable in phaser 3

在我的 Phaser 游戏中,我将箭头定义为在 if 语句中使用 "let" 关键字的变量。我通过将它们显示为精灵来做到这一点。但是,我需要在箭头击中目标后显示奖牌。我还希望奖牌在前一枚奖牌的右侧显示 30 像素,当然是从显示的第一枚奖牌开始。完成这一切的最佳方式是什么?

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Video Game</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script type="text/javascript">
    //Configurations for the physics engine
    var physicsConfig = {
        default: 'arcade',
        arcade: {
            debug: false //CHANGE THIS TO TRUE TO SEE LINES
        }
    }
    //Configurations for the game itself
    var config = {
        type: Phaser.AUTO,
        width: 800,
        height: 600,
        physics: physicsConfig,
        scene: {
            preload: preload,
            create: create,
            update: update,
            render: render
        }
    };
    //Start the game
    var game = new Phaser.Game(config);

    function preload ()
    {   
        //Images
        this.load.image('sky', 'assets/images/sky.png');
        this.load.image('target', 'assets/images/target.png');
        this.load.image('ground', 'assets/images/ground.png');
        this.load.image('arrow', 'assets/images/arrow.png');
        this.load.image('gold_medal', 'assets/images/goldmedal.png');
        this.load.image('silver_medal', 'assets/images/silvermedal.png');
        this.load.image('bronze_medal', 'assets/images/bronzemedal.png');
        //Spritesheets
        this.load.spritesheet('archer', 'assets/spritesheets/archer_sprites.png', {frameWidth: 128, frameHeight: 128});
        this.load.spritesheet('rings', 'assets/spritesheets/rings_sprite.png', {frameWidth: 320, frameHeight: 320});
        //Audio
        this.load.audio('arrow_shot', 'assets/sounds/arrow_shooting.mp3');
    }
    function create ()
    {   
        //Load all the images that won't move
        this.add.image(400, 300, 'sky');
        this.add.image(210, 200, 'ground');

        //Create the archer/player
        this.player = this.physics.add.sprite(100, 410, 'archer');
        this.player.setBounce(0.2);
        this.player.setCollideWorldBounds(true);

        //Shooting animation
        this.anims.create({
            key: 'shoot',
            frames: this.anims.generateFrameNumbers('archer', {start : 0, end: 4}),
            frameRate: 20,
            repeat: 0
        });

        //Rings animation
        this.anims.create({
            key: 'rings_anim',
            frames: this.anims.generateFrameNumbers('rings', {start : 0, end : 69}),
            frameRate: 10,
            repeat: 0
        })
        //Play the animation on start
        this.rings = this.physics.add.sprite(300, 40, 'rings');
        this.rings.anims.play('rings_anim', true);

        //Create the target
        this.target = this.physics.add.sprite(530, 365, 'target');
        this.target.setSize(115, 95).setOffset(70, 130); //TARGET HITBOX
        this.target.enableBody = true;
        this.target.setImmovable();

        //Create an array for arrows for later
        this.arrows = [];

        //Create an array for medals for later
        this.medals = [];

        //Get keypresses
        this.cursors = this.input.keyboard.createCursorKeys();
        //Assign input for spacebar
        this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

        //Play sound when the arrow is shot
        this.arrowSound = this.sound.add('arrow_shot');

        //Make the arrows collide with the target
        this.physics.add.collider(this.arrows, this.target)
    }
    function update ()
    {   
        //Declare constants for movement
        const playerMoveAmt = 200;
        const arrowMoveAmt = 1500;
        this.player.setDrag(2000);

        //Rotation of the player
        if (this.cursors.up.isDown && this.player.angle > -45) {
            this.player.angle -= 1;}

        if (this.cursors.down.isDown && this.player.angle < 0) {
            this.player.angle += 1;}

        //Shooting with the spacebar
        if (Phaser.Input.Keyboard.JustDown(this.spacebar)) {

            //Animate the shooting
            this.player.anims.play('shoot', true);

            //Arrow shooting
            let arrow = this.physics.add.sprite(this.player.x, (this.player.y + 20), 'arrow');
            arrow.enableBody = true;
            arrow.body.immovable = false;

            //Edit arrow hitbox 
            arrow.setSize(50, 15).setOffset(5, 50);

            arrow.setGravityY(3600); //Gravity will affect the arrows

            //Arrow speeds
            arrow.setVelocityX(arrowMoveAmt);
            arrow.setVelocityY((this.player.angle * 50));

            this.arrows.push(arrow); //Add arrow to the arrow created earlier
            this.arrowSound.play(); //Play the sound
        }

        else if(this.target.body.touching.left) {

            //Loop to create multiple arrows
            for (i = 0; i < this.arrows.length; i += 1) {
                newarrows = this.arrows[i];
                newarrows.setGravityY(0);
                newarrows.setVelocityX(0);
                newarrows.setVelocityY(0);
                //Reset the player angle for difficulty
                this.player.angle = 0;
                //Gold medal
                if (410 < newarrows.y && newarrows.y < 435) {
                    let goldMedal = this.add.image(300, 200, 'gold_medal');
                    goldMedal;
                }
                //Silver medal
                else if (395 < newarrows.y && newarrows.y < 450) { 
                    this.add.image(300, 200, 'silver_medal');
                }
                //Bronze medal
                else if (380 < newarrows.y && newarrows.y < 460) {
                    this.add.image(300, 200, 'bronze_medal');
                }
            }
        }
    }
    function render() {
    }
</script>
</body>
</html>

我尝试使用 "if (newArrows.length == 5)" 和 "if (this.arrows.length == 5)" 来做到这一点。我还尝试将图像定义为变量并调用它来显示,然后将其推送到数组,就像箭头一样。

希望所有这些都有意义

我找到了解决方案:

  • 首先,我把之前做的for循环改成了while loop 因为它更适合这个用例。

  • 其次,我创建了一个变量,在while循环之前,命名为arrowOnTargetPositionX&设置初始值为200.

  • 第三,我将变量设置为它自己的值+30(就像你想要的相同数量的像素)。

  • 四个,我从循环中删除了if else语句逻辑并创建了一个function 名为 **getMedal(arrowOnTargetPositionX);**.

  • Fith,我在下面声明了function&传递参数值来更新位置新奖牌的水平排列。

终于,这是结果码:

function update ()
{   
    //Declare constants for movement
    const playerMoveAmt = 200;
    const arrowMoveAmt = 1500;
    this.player.setDrag(2000); 

    //Rotation of the player
    if (this.cursors.up.isDown && this.player.angle > -45) {
        this.player.angle -= 1;}

    if (this.cursors.down.isDown && this.player.angle < 0) {
        this.player.angle += 1;}

    //Shooting with the spacebar
    if (Phaser.Input.Keyboard.JustDown(this.spacebar)) {

        //Animate the shooting
        this.player.anims.play('shoot', true);

        //Arrow shooting
        let arrow = this.physics.add.sprite(this.player.x, (this.player.y + 20), 'arrow');
        arrow.enableBody = true;
        arrow.body.immovable = false;

        //Edit arrow hitbox 
        arrow.setSize(50, 15).setOffset(5, 50);

        arrow.setGravityY(3600); //Gravity will affect the arrows

        //Arrow speeds
        arrow.setVelocityX(arrowMoveAmt);
        arrow.setVelocityY((this.player.angle * 50));

        this.arrows.push(arrow); //Add arrow to the arrow created earlier
        this.arrowSound.play(); //Play the sound
    }

    else if(this.target.body.touching.left) {
        let i = 0;

        // Set initial horizontal position of new medals
        let arrowOnTargetPositionX = 200;

        //Loop to create multiple arrows
        while (i < this.arrows.length) {
            newArrows = this.arrows[i];
            newArrows.setGravityY(0);
            newArrows.setVelocityX(0);
            newArrows.setVelocityY(0);

            // Add 30 to new medals horizontal position
            arrowOnTargetPositionX = arrowOnTargetPositionX + 30;

            // Calls the function to get medal & passed the variable as an argument
            getMedal(arrowOnTargetPositionX);

            i++;
        }
    }

    // function to get different medals
    getMedal = (value) => {
        //Gold medal
        if (410 < newArrows.y && newArrows.y < 435) {
            this.add.image(value, 180, 'gold_medal');
        }
        //Silver medal
        else if (395 < newArrows.y && newArrows.y < 450) { 
            this.add.image(value, 250, 'silver_medal');
        }
        //Bronze medal
        else if (380 < newArrows.y && newArrows.y < 460)  {
            this.add.image(value, 320, 'bronze_medal'); 
        }
    }
}

编辑:

要仅显示最多 5 个奖牌,请使用此代码段:

//Loop to create multiple arrows
while (i < this.arrows.length) {
    newArrows = this.arrows[i];
    newArrows.setGravityY(0);
    newArrows.setVelocityX(0);
    newArrows.setVelocityY(0);

    // Add 30 to new medals horizontal position
    arrowOnTargetPositionX = arrowOnTargetPositionX + 30;

    if(this.arrows.length <= 5) {
        // Calls the function to get medal & passed the variable as an argument
        getMedal(arrowOnTargetPositionX);
    }

    i++;
}