我正在尝试制作一款玩家持有武器,但武器类型可以改变的游戏。我正在尝试设置每个武器的"材质"或"特征",它应该改变图像的路径,因此正确的图像被绘制到屏幕上。然而,它似乎不起作用。下面是我当前的代码:
let magnet_image = new Image();
magnet_image.src = "assets/images/weapons/magnet.png";
magnet = new Weapon(magnet_image);
class Weapon {
image_path;
constructor (image_path) {
image_path.src.replace(/magnet/gi, "magnet_black");
console.log(image_path)
this.x = player.x + player.width / 2;
this.y = player.y + player.height / 2;
this.width = 50;
this.height = 50;
this.angle = 0;
this.material = "";
this.image = image_path;
this.distance = 50;
}
}
我试图从"assets/images/weapons/magnet.png"
切换到"assets/images/weapons/magnet_black.png"
,但console.log语句返回"assets/images/weapons/magnet.png"
(AKA不正确的路径)。即使是默认的磁铁图像也绘制在屏幕上,而不是黑色的磁铁。我该如何解决这个问题?
试试这个:
const regex = /magnet/gi
let newWord = magnet.replace(regex, 'magnet_black')
console.log(newWord)
let magnet = 'assets/images/weapons/magnet.png'
const regex = /magnet/gi
magnet.replace(regex, 'magnet_black')
console.log(magnet)
magnet = magnet.replace(regex, 'magnet_black')
console.log(magnet)
哦,哈哈,我想我已经弄明白了。您没有将替换的字符串分配给image_path.src