我正在尝试将精灵添加到游戏引擎中,并且尝试了很多事情。问题在于游戏可以运行,但我的图像从未显示。 编辑:我发现通过将图像和src放在钱币类构造函数中使其呈现。
我尝试过window.onLoad,img.onLoad,将vars放入构造函数中,将其分成2个函数(加载和绘制)。
class gameObject {
constructor(x,y,id){
this.x = x;
this.y = y;
this.id = id;
var velX, velY, width, height;
}
drawRect(){
c.fillRect(this.x, this.y, this.width, this.height);
}
drawSprite(url){
this.img = new Image();
this.img.src = url;
this.img.onload = function(){
function draw(){
c.drawImage(this.img, this.x, this.y, this.width, this.height)
}
draw();
}
}
move(){
this.x += this.velX;
this.y += this.velY;
}
}
class Coin extends gameObject{
constructor(x,y,id,img){
super(x,y,id);
this.velX = 0;
this.velY = 0;
this.width = 32;
this.height = 32;
}
tick(){
this.move();
}
render(){
this.drawSprite("coin.png");
}
}
我需要显示图片,但该图片不显示并且游戏仍在运行。
答案 0 :(得分:1)
根据MDN,library(tidyverse)
input %>%
mutate(new = str_extract(V3, "(Up|Down)"),
new2 = str_extract(V3, "Summer|Winter"),
new3 = str_extract(V3, str_c("(", str_c(month.name,
collapse = "|"), ").*$"))) %>%
select(-V3) %>%
group_by(V1, V2, new, new2, new3) %>%
mutate(rn = row_number()) %>%
ungroup %>%
spread(new, V4) %>%
rename_at(vars(starts_with('new')), ~ str_c("V", 3:4)) %>%
mutate(V4 = replace_na(V4, "")) %>%
select(-rn)
的值在this
中为undefined
,因为它是类声明内的嵌套函数-并且在严格模式下解析类声明。
一种解决方案是
function draw
使用箭头功能,以便在将词法draw
赋给变量时捕获它,this
值引用类实例而不是图像元素的位置,并且this
属性之前先为其分配图像onload
处理程序:src
进一步的测试表明,CanvasRenderingContext2D方法drawSprite(url){
let draw = ()=>c.drawImage(this.img, this.x, this.y, this.width, this.height);
this.img = new Image();
this.img.onload = draw;
this.img.src = url;
}
无法处理x和y的未定义值,如果是,则不会绘制任何内容。
drawImage
将未定义的值默认为零应该有助于随着开发的进一步发展。
答案 1 :(得分:0)
好,所以我发现的唯一解决方案是将this.img和this.img.src移到如下所示的类中
class Coin extends gameObject{
constructor(x,y,id){
super(x,y,id);
this.velX = 0;
this.velY = 0;
this.width = 32;
this.height = 32;
this.img = new Image();
this.img.src = "coin.png";
}
tick(){
this.move();
}
render(){
this.drawSprite()
}
}
而且显然在等待img加载时也会导致它不显示,所以我就这样做了。
drawSprite(){
c.drawImage(this.img, this.x, this.y, this.width, this.height);
}
我还将其保留为draw sprite函数,因为我将使其也从Sprite表中读取