javascript - 使用函数参数作为值?
问题描述
我最近开始学习 JavaScript,并且正在尝试制作一个小型平台游戏。我有一些基本的功能,比如重力、运动和对象创建。但我想让世界构建更容易一些,所以我做了一个函数来创建块。一切都很好,但是为了在玩家和方块之间产生碰撞,我希望能够从那些特定的方块中获取变量,并用它来阻止我的角色。现在我将块设置为一个变量,并尝试调用该变量,但它显示为红色。无论如何我可以解决这个问题吗?还是有更好的碰撞方式?
此处并未显示所有代码,仅显示相关内容。
var b1;
function block(x, y, w, h, color) {
c.fillStyle = color;
c.fillRect(x, y, w, h);
}
function update() {
if((pX >= b1.x - pW) && (pY >= b1.y - pH)) {
pX = b1.x - pW;
}
}
function draw() {
b1 = block(500, 350, 100, 100, 'gray');
}
解决方案
这不是创建对象的唯一方法,有很多方法,但它是与您拥有的代码最匹配的方法。
对象是 JavaScript 的基本构建块(如 Java 的类),在开始使用它们之前获得更深入的理解是值得的
基本示例
// 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, 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, y, w, h, 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, 350, 100, 100, 'gray');
b1.draw();
或者
const Block = (x, y, w, h) => ({x, y, w, h});// this method does not require new operator
var b1 = Block(500, 350, 100, 100, 'gray');
drawBlock(b1);
function drawBlock(block) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.w, block.h);
}
或者
const blockCommon = {
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
},
};
const Block = (x, y, w, h) => ({x, y, w, h, ...blockCommon});
var b1 = Block(500, 350, 100, 100, 'gray');
b1.draw();
或十几种或更多创建对象的方法。
推荐阅读
- powershell - 压缩归档任务在 SSIS 中失败,文件为 1.25GB
- javascript - 是导出顶级变量引用 javascript 中的副作用
- typescript - 如何以编程方式获取变量的类型并将其用作函数参数的类型?
- c - 使用 vcpkg 和 VisualStudio 时 SDL2 的链接器错误
- sql - 错误 1054 (42S22):尝试通过 cmd 在 sql 中创建序列时,“字段列表”中的未知列“sq.nextval”
- html - 更改 Web 表单中按钮输入的元素
- c# - 仅设置 TLS 1.3 时无响应
- ios - 与控制中心相同的当前 ViewController 在 iPhone 中工作
- javascript - 编辑条目时电子应用程序不更新条目
- ruby-on-rails - Rails 6 中的 Rails 红色开发错误页面在哪里?