简体   繁体   中英

how do i compare a variable to more than one value?

I have this code, that is supposed to make a simple game where you have a paddle that you need to use to catch the balls. Code:

var h = 350;
var w = 350;
var x = 0;
var bx = 0;
var by = 0;
var bys = 5;
var score = 0;
var hit = false;

//inicial size: 350,350.
function setup(){
    createCanvas(w,h);
    bx = random(10,340);
}

function draw(){
    background(50);
    drawPad();
    drawBall();
    drawScore();
    if(hit){
        bx = random(10,340);
        hit=false;
    }
}

function drawPad(){
    fill(255);
    noStroke();
    if(mouseX>0||mouseX<290){
        x = mouseX;
        rect(x,320,60,20);
    }
    if(mouseX>290){
        x=290;
        rect(x,320,60,20);
    }
    if(mouseX<0){
        x= 0;
        rect(x+60,320,60,20);
    }
}

function drawBall(){
    if(by!=310){
        fill(255,20,75);
        by += bys;
        ellipse(bx,by,10,10);   
    }else{
        score++;
        by = -100;
        hit = true;
    }
}

function drawScore(){
    text(score,10,10);
}

And I want to compare my bx to more than 1 value, I want to compare it to (mouseX,mouseX+10) and (mouseX-10,mouseX). Please help me if you know how I should complete my code. Thanks.

I'd wrap it in a little function like so:

function mouseXIsInRange () {
  var nameThatDescribesFirstComparison = (bx === mouseX && bx === mouseX + 10);
  var nameThatDescribesSecondComparison = (bx === mouseX && bx === mouseX - 10);
  return nameThatDescribesFirstComparison && nameThatDescribesSecondComparison;
}

and call it like so:

if (mouseXIsInRange()) {
  // do something
}

It's good to name your functions and variables in a way that makes your code easy to read, especially when you start getting into comparison logic. Good naming will save you a ton of headache when you go to re-read your code. Good luck!

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