我正在为游戏创建一个非常基本的 Sprite (它是在 Canvas/Context/LineTo 中绘制的)。我希望它的表达根据两种不同的绘制方法随机变化。这是我的尝试:
drawFace = function () {
if (Math.random() < 0.05) {
Player.drawhappyface(context);
}
else if (Math.random() < 0.1) {
Player.drawsadface(context);
}
}
drawFace();
我可以确认drawhappyface和drawsadface绘制方法独立于该函数工作(分别绘制微笑和皱眉)。但使用这个函数及其逻辑,它们根本就不会被绘制(玩家完全没有脸)。那么,我写错了吗?我受到以下模拟的启发,该模拟也使用 Math.random 不断地对表达式进行动画处理:http://www.blobsallad.se/
如果我像这样编写函数,那么 Canvas 上绝对不会绘制任何内容(所有其他 Sprite 等也不会绘制):
drawFace = function (context) {
if (Math.random() < 0.05) {
Player.drawhappyface(context);
}
else if (Math.random() < 0.1) {
Player.drawsadface(context);
}
}
drawFace();
最佳答案
问题可能是您在两个 if
语句中调用 Math.random()
,然后它们将具有不同的值。仅调用 Math.random()
一次,并在每次需要/调用 drawFace
时保存该值,尝试如下所示:
drawFace = function () {
var randomNumber = Math.random();
console.log(randomNumber);
if (randomNumber < 0.05) {
console.log('randomNumber < 0.05');
}
else if (randomNumber < 0.1) {
console.log('randomNumber < 0.1');
}
}
drawFace();
如果你只是想画快乐或悲伤的脸,你可以做更简单的if else
drawFace = function () {
var randomNumber = Math.random();
console.log(randomNumber);
if (randomNumber < 0.5) {
console.log('draw happy face');
} else {
console.log('draw sad face');
}
}
drawFace();
关于JavaScript Canvas——是否可以依赖Math.random进行绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366128/