因此,如果要按下某个特定的键,我将尝试编写某种代码,将某种形状转换为另一种形状。到目前为止,我还停留在第一个形状。如何写我的“ var musculus”更改为keyTyped上的屈肌或伸肌功能?
var musculus;
function draw() {
musculus = ellipse(30, 30, 20, 20);
function keyTyped() {
if (key === 'a') {
musculus = flexor;
} else if (key === 'b') {
musculus = extensor;
}
}
}
function flexor() {
ellipse(56, 46, 55, 55);
}
function extensor() {
square(30, 20, 55, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
答案 0 :(得分:0)
您可以将musculus
设为自己的函数,可以调用该函数来绘制圆。然后,您可以使用名为currentShape
的全局变量,该变量存储对要绘制的当前形状的引用(即,绘制椭圆的函数)。当您要更改形状时(在keyPress
中,可以将currentShape
重新分配为新的功能,以绘制新的形状。
还要注意,在p5js中,您的keyTyped()
函数应该位于其他任何函数之外。
var currentShape = musculus;
function draw() {
background(255); // draw background (remove any previously drawn shapes)
currentShape();
}
function keyTyped() {
if (key === 'a') {
currentShape = flexor;
} else if (key === 'b') {
currentShape = extensor;
}
}
function musculus() {
ellipse(30, 30, 20, 20);
}
function flexor() {
ellipse(56, 46, 55, 55);
}
function extensor() {
square(30, 20, 55, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
答案 1 :(得分:0)
您的代码即将运行,您只需要进行一些更改。
删除musculus = ellipse(30, 30, 20, 20);
中的行draw()
。
绘图每帧运行一次,因此小肌肉不断设置为ellipse(30, 30, 20, 20)
musculus
已设置但从未使用过,请将musculus;
添加到draw()
中,以便在框架上使用。
将keyTyped()
移到draw()
之外,以便P5js可以看到和使用它。
keyTypes()
是正确的,但您不仅需要为函数名称设置musculus
,还需要为函数设置()
。只需在每个函数名称中添加musculus = flexor();
。即。 var musculus;
function draw() {
musculus;
}
function keyTyped() {
if (key === 'a') {
musculus = flexor();
} else if (key === 'b') {
musculus = extensor();
}
}
function flexor() {
ellipse(56, 46, 55, 55);
}
function extensor() {
square(30, 20, 55, 20);
}
您可以对该脚本进行很多改进,但是您已经有了一个良好的开端。
固定代码
musculus
更好的解决方法
在我的重写中,我将draw()
的值设置为一个单词(也称为字符串),该单词在if statement
中用于调用background('white')
中的相应函数。我还使用var musculus;
function draw() {
background(255);
if (musculus === 'flexor') {
flexor();
} else if (musculus === 'extensor') {
extensor();
}
}
function keyTyped() {
if (key === 'a') {
musculus = 'flexor';
} else if (key === 'b') {
musculus = 'extensor';
}
}
function flexor() {
ellipse(56, 46, 55, 55);
}
function extensor() {
square(30, 20, 55, 20);
}
来清除屏幕,然后绘制新框架。
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
users/${createdUser.user.uid}