当您在javascript中单击圆圈时,如何使其移动? [英] How to get a circle to move when you click on it in javascript?
问题描述
我正在为一个班级制作一个基于3x3网格的打地鼠游戏,但是我无法让该地鼠(使用p5.js制作的椭圆)移动到另一个网格上点击.我希望它在7秒钟后自动移动,这是我使用功能sleep(毫秒)实现的,但是如果玩家在7秒钟之前单击痣,那么我希望它立即切换网格正方形.这是我的mousePressed和moveCircle代码.
I'm making a whack-a-mole game based on a 3x3 grid for one of my classes but i'm having trouble getting the mole(an ellipse made using p5.js) to move to a different grid square on click. I want it to automatically move after 7 seconds which i achieved using function sleep(milliseconds), but if the player clicks the mole before the 7 seconds is up then I want it to switch grid squares right then. This is my code for mousePressed and moveCircle.
function mousePressed() {
var distance = int(dist(mouseX, mouseY, moleX, moleY));
if(distance <= circleDiameter/2 ) {
moveCircle();
score += 1;
}
document.getElementById('playerScore').innerHTML=score;
}
function moveCircle(){
var randomX = [110, 260, 410];
var randomY = [95, 245, 395];
var moleX = random(randomX);
var moleY = random(randomY);
}
推荐答案
您的sleep()
函数不是不是如何在P5.js或JavaScript中处理计时的方法.
Your sleep()
function is not how you should handle timing in P5.js, or in JavaScript in general.
您的sleep()
函数会导致您的程序完全无响应,这是很糟糕的,原因有很多.一个问题是您的事件代码将不会触发,这就是您所看到的问题.
Your sleep()
function causes your program to become completely unresponsive, which is bad for a lot of reasons. One problem is that your event code will not trigger, which is the problem you're seeing.
相反,您需要使用millis()
函数或frameCount
变量来处理计时,而不会阻塞整个程序.这是一个小例子:
Instead, you need to use the millis()
function or the frameCount
variable to handle your timing without blocking your whole program. Here's a small example:
function setup() {
createCanvas(200,200);
background(32);
}
function draw(){
// 60 frames is 1 second
if(frameCount % 60 == 0){
ellipse(random(width), random(height), 25, 25);
}
}
此代码将frameCount
变量与%
模数运算符一起使用,以检查是否已经过了1秒.换句话说,该程序每秒绘制一个圆圈.
This code uses the frameCount
variable along with the %
modulus operator to check whether 1 second has elapsed. In other words, this program draws a circle every second.
您需要执行类似的操作来移动痣,即使痣正在等待",这也将允许触发您的事件代码.
You need to do something similar to move your mole, which will allow your event code to be fired even while the mole is "waiting".
这篇关于当您在javascript中单击圆圈时,如何使其移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!