在 p5.js 中交换变量

Swapping variable in p5.js

我在我的程序中定义了一个名为 fighter 的变量。我有一个 if keyPressed 函数,它根据键选择特定图像。我遇到的问题是图像正在交换但与原始图像重叠。我还尝试在原来的位置添加一个带有战斗机的 else 语句,但仍然是相同的响应。

var fighter;
var stance;
var kick;
var jab;
var cross;
var mx; //Use to constrain fighter to center of circle
var my;

function preload(){
    stance = loadImage("img/stance.svg");
    kick = loadImage("img/kick.svg");
    jab = loadImage("img/jab.svg");
    cross = loadImage("img/cross.svg");
};

function setup(){
    createCanvas(1280,720);
};



function draw(){
    background(0, 246, 255);
    fill("red");
    ellipse(width/2,height/2,500,500);
    mx = constrain(mouseX,width/2-250,width/2+250);
    my = constrain(mouseY,height/2-250,height/2+250);
    fighter = image(stance,mx,my);


    if(keyIsPressed){
        if((key == "a" || key == "A")){
            fighter = "";
            fighter = image(jab,mx,my);
        }
        else if ((key == "w" || key == "W")) {
            fighter = image(cross,mx,my);
        }
        else if ((key == "s" || key == "S")) {
            fighter = image(kick,mx,my);
        } 
    };

};

出于某种原因,您将 fighter 设置为 image() 函数返回的值。这没有多大意义。

相反,我认为您想将 fighter 设置为其中一个图像,然后将 fighter 传递给 image() 函数。像这样:

fighter = stance;

if(keyIsPressed){
    if((key == "a" || key == "A")){
        fighter = jab;
    }
    else if ((key == "w" || key == "W")) {
        fighter = cross
    }
    else if ((key == "s" || key == "S")) {
        fighter = kick;
    } 
}

image(fighter, mx,my);