问题描述
最近我已经开始使用JavaScript,并且我正在尝试制作一个小型平台游戏。我有一些基本功能,例如重力,运动和对象创建。但是我想简化世界构建,所以我创建了一个创建块的函数。一切正常,但是要在玩家和方块之间产生冲突,我希望能够从那些特定方块中获取变量,并以此来停止我的角色。现在,我将代码块设置为一个变量,并尝试调用该变量,但结果显示为红色。反正我能解决这个问题吗?还是有更好的碰撞方法?
var b1;
function block(x,y,w,h,color) {
c.fillStyle = color;
c.fillRect(x,h);
}
function update() {
if((pX >= b1.x - pW) && (pY >= b1.y - pH)) {
pX = b1.x - pW;
}
}
function draw() {
b1 = block(500,350,100,'gray');
}
解决方法
您可以使用函数通过Objects创建new operator
这不是创建对象的唯一方法,有很多,但这是与您的代码最接近的匹配。
Objects是JavaScript的基本构建块(如Java的类),在开始使用JavaScript之前需要加深了解。
基本示例
// It is customary for object instantiated via new to have capitalized names
function Block(x,y,w,h,color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
var b1 = new Block(500,350,100,'gray');
drawBlock(b1);
function drawBlock(block) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x,block.y,block.w,block.h);
}
function update() {
if((pX >= b1.x - pW) && (pY >= b1.y - pH)) {
pX = b1.x - pW;
}
}
或
// It is customary for object instantiated via new to have capitalized names
function Block(x,color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
}
Block.prototype = {
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.w,this.h);
},};
var b1 = new Block(500,'gray');
b1.draw();
或
const Block = (x,h) => ({x,h});// this method does not require new operator
var b1 = Block(500,'gray');
drawBlock(b1);
function drawBlock(block) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x,block.h);
}
或
const blockCommon = {
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x,};
const Block = (x,...blockCommon});
var b1 = Block(500,'gray');
b1.draw();
或十二种或更多种创建对象的方法。