javascript - JavaScript 如何获取一个值并将其放入函数中
问题描述
您可以在此链接中查看我的所有代码
并且有带有github页面的演示链接
现在,当我开始游戏时,我可以看到游戏环境。但我想让它选择我想要的角色。
所以我使用 VEX Libaray 来使用询问什么 Character 的对话框。你可以查看我的截图。
因此,当我单击每个按钮时,它可以像这样打印。
在那之后,我唯一要做的就是给 this.sprite 赋值。但我不知道如何将其放入 Player。
核心代码在这里。
// To choose Character with VEX Library
function click1() {
vex.dialog.open({
message: 'Which character do you want to play?',
buttons: [
$.extend({}, vex.dialog.buttons.NO, {
className: 'vex-dialog-button-primary-horizontal',
text: 'Char-Boy',
click: function (e) {
this.value = 'char-boy';
this.close();
}
}),
$.extend({}, vex.dialog.buttons.NO, {
className: 'vex-dialog-button-primary-horizontal',
text: 'Char-Cat-Girl',
click: function (e) {
this.value = 'char-cat-girl';
this.close();
}
}),
$.extend({}, vex.dialog.buttons.NO, {
className: 'vex-dialog-button-primary-horizontal',
text: 'Char-Horn-Girl',
click: function (e) {
this.value = 'char-horn-girl';
this.close();
}
}),
$.extend({}, vex.dialog.buttons.NO, {
className: 'vex-dialog-button-primary-horizontal',
text: 'Char-Pink-Girl',
click: function (e) {
this.value = 'char-pink-girl';
this.close();
}
}),
$.extend({}, vex.dialog.buttons.NO, {
className: 'vex-dialog-button-primary-horizontal',
text: 'Char-Princess-Girl',
click: function (e) {
this.value = 'char-princess-girl';
this.close();
}
})
],
callback: function (value) {
// char-boy','char-cat-girl','char-horn-girl','char-pink-girl','char-princess-girl
if (value === 'char-boy') {
console.log('You choose Char-boy');
return value;
} else if (value === 'char-cat-girl') {
console.log('You choose Char-Cat-Girl');
return value;
} else if (value === 'char-horn-girl') {
console.log('you choose Char-Horn-Girl');
return value;
} else if (value === 'char-pink-girl') {
console.log('You Choose Char-Pink-Girl');
return value;
} else if (value === 'char-princess-girl') {
console.log('You Choose Char-Princess-Girl');
return value;
} else {
console.log('Choose Nothing');
return value;
}
}
})
}
let Player = function (x, y, speed, value) {
this.x = x;
this.y = y;
this.speed = speed;
this.sprite = 'images/' + value + '.png';
};
解决方案
我猜你稍后会在初始化游戏时创建一个新的 Player 实例,所以也许你可以使用 Player 的原型来设置值,如下所示:
let Player = function (x, y, speed) {
this.x = x;
this.y = y;
this.speed = speed;
this.sprite = 'images/' + this.value + '.png';
};
Player.prototype.value = 'char-boy'; // this should go inside vex callback
console.log(new Player(50,50,100).sprite); // this should print "images/char-boy.png"
附上对原型文档的引用:https ://www.w3schools.com/js/js_object_prototypes.asp
推荐阅读
- amazon-web-services - 如何在手机/短信中确认 AWS SNS 订阅?
- scala - 迭代一个 RDD[A],其中 A 包含 List[B]
- java - 使用java连接到windows远程服务器并修改一些文件?
- django - Python Django Ubuntu Server 16.04 aws 内部服务器错误
- javascript - javascript中的简单while循环不遵守限制
- sql - 在 SELECT 中使用子查询会返回我无法解释的错误
- memory - Pentaho:阻止这一步,直到步骤完成
- swift - 告诉 UITableView 哪些数据应该在 Swift 中显示的最佳方法
- html - 拿不到
- 显示在 :hover of another
- c++ - 如何用cmake构建凯特?