繁体   English   中英

使用函数参数作为值?

[英]Use Function Parameters as Values?

我最近开始学习 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'); }

您可以使用函数来使用new 运算符创建对象

这不是创建对象的唯一方法,有很多方法,但它是最接近您拥有的代码的方法。

对象是 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();

或十几种或更多创建对象的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM