How to get a circle to move when you click on it in javascript?

元气小坏坏 提交于 2019-12-13 05:06:02

问题


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);

   }

回答1:


Your sleep() function is not how you should handle timing in P5.js, or in JavaScript in general.

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.

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);   
    }
}

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".




回答2:


int(dist(mouseX, mouseY, moleX, moleY))

This int keyword does not make sense. If you want it to be a whole number, use the Math.round() function (or just round() in p5js).

Try console.loging the distance variable.



来源:https://stackoverflow.com/questions/49619295/how-to-get-a-circle-to-move-when-you-click-on-it-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!