简体   繁体   中英

HTML canvas and javascript trying to recreate a firing action https://codepen.io/sijbc/pen/WNoqLwz

    I have a simple mouse click function which makes a small ellipse 
    move up from the paddle to simulate a firing motion. However it only fires once. 
    See the code pen.
    
    
    
    Code Pen link
    <https://codepen.io/sijbc/pen/WNoqLwz>

function mouseClickFunction(event){
    cannonFired = true
    console.log(event.clientX)
    fireX = event.clientX ;
}

function fireCannon(){
  if(cannonFired){
    x = fireX 
    context.fillStyle = "#0095DD"
    context.beginPath()
    context.arc(x, y, 10, 0, 2 * Math.PI, false)
    context.fill()
    y -=5.5
    if ( y <= 0){
      cannonFired = false
      return
    }
  }
}

The above code works to fire the cannon once but doesn't work on the repeat cycle. As in it only fires once and then cannot reset.

I have tried setting the boolean back to false but it still doesn't work.

You reset-ed the boolean, but not your y coordinates. If you look at your if-else statement here

if ( y <= 0){
  cannonFired = false
  return
}

Once y <= 0 once, it will forever be <= 0 because you did not reset y coordinates. This means the starting position of the shell fired by your cannon is already out of screen - so technically the cannon is still firing, just that you dont see it on the screen.

You need to reset it like so

if ( y <= 0){
  cannonFired = false;
  y =canvas.height-30;
  return;
}

It will work now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM