首页 > 解决方案 > 使用函数参数作为值?

问题描述

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

标签: javascriptfunction2dgame-physicscollision

解决方案


您可以使用函数使用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();

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


推荐阅读