Как вызвать функцию и продолжить, нажав клавишу один раз? - PullRequest
2 голосов
/ 20 февраля 2020

Я хочу, чтобы функция ball.move(); в приведенном ниже коде продолжала работать после однократного нажатия пробела. Это работает, только если я продолжаю нажимать клавишу пробела.

void draw() {

if (start == true) {ball.move();}

}
void keyPressed() {

  if (key == ' '){start = true;}    

}

void keyReleased() {

  if (key == ' ') {start = false;}

} 

Это игра для понга, которую я делаю, и каждый раз, когда мяч ударяется о край, он телепортируется в центр холста. Вот когда я хочу снова начать движение мяча вручную.

Вот весь код:

Ball ball;
Player player1;
Player player2;

int scorePlayer1 = 0;
int scorePlayer2 = 0;

PFont font;

boolean start;

void setup() {

  size(1368,768);
  frameRate(144);
  noStroke();

  ball = new Ball(width/2, height/2, 30);
  player1 = new Player(15, height/2, 30, 150);
  player2 = new Player(width-15, height/2, 30, 150);

  ball.speedX = 10;

}

void draw() {

  background(0);

  textSize(40);
  textAlign(CENTER);
  font = loadFont("Arial-Black-48.vlw");
  textFont(font);

  ball.display();
  if (start == true) {ball.move();}
  player1.run();
  player2.run();

  //Score 
  if (ball.left() < 0) {
    scorePlayer2 = scorePlayer2 + 1;
    ball.x = width/2;
    ball.y = height/2;
  }

  if (ball.right() > width) {
    scorePlayer1 = scorePlayer1 +1;
    ball.x = width/2;
    ball.y = height/2;
  }

  text(scorePlayer1, width/2-75, 50);
  text(scorePlayer2, width/2+75, 50);

  //Collision
  if (ball.top() < 0) {
    ball.speedY = -ball.speedY;
  }

  if (ball.bottom() > height) {
    ball.speedY = -ball.speedY;
  }

  if (ball.left() < player1.right() && ball.y > player1.top()-10 && ball.y < player1.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player1.y, -player1.h/2, player1.h/2, -5, 5);
  }

  if (ball.right() > player2.left() && ball.y > player2.top()-10 && ball.y < player2.bottom()+10) {
    ball.speedX = -ball.speedX;
    ball.speedY = map(ball.y - player2.y, -player2.h/2, player2.h/2, -5, 5);
  }

  if (player1.bottom() > height) {
    player1.y = height-player1.h/2;  
  }

  if (player1.top() < 0) {
    player1.y = player1.h/2;
  }

  if (player2.bottom() > height) {
    player2.y = height-player1.h/2;  
  }

  if (player2.top() < 0) {
    player2.y = player1.h/2;
  }

}

//Movement
void keyPressed() {

  player1.pressed((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.pressed((keyCode == UP), (keyCode == DOWN));   

  if (key == ' '){start = true;}    

}

void keyReleased() {

  player1.released((key == 'w' || key == 'W'), (key == 's' || key == 'S'));
  player2.released((keyCode == UP), (keyCode == DOWN));

  if (key == ' ') {start = false;}

}

class Ball {

  float x;
  float y;
  float d;
  float speedX;
  float speedY;
  color c;

  //Constructor
  Ball(float tempX, float tempY, float tempD){

    x = tempX;
    y = tempY;
    d = tempD;
    speedX = 0;
    speedY = 0;
    c = (255);

  }

  void display() {

    fill(c);
    ellipse(x,y,d,d);

  }

  void move() {

    x = x + speedX;
    y = y + speedY;

  }

  //Collision help
  float top() {
    return y-d/2;
  }

  float bottom() {
    return y+d/2;
  }

  float left() {
    return x-d/2;
  }

  float right() {
    return x+d/2;
  }

}

class Player {

  float x, y;
  float w, h;
  float speedY = 0.0;
  color c;
  boolean moveUp = false, moveDown = false;

  //Constructor
  Player(float tempX, float tempY, float tempW, float tempH){

    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    speedY = 0;
    c = (255);

  }

  void run() {

    display();
    move();

  }

  void display() {

    fill(c);
    rect(x-w/2, y-h/2, w, h);

  }

  //Movement
  void move() {

    if (!moveUp && !moveDown) {speedY = speedY * 0.85;}
    if (moveUp)               {speedY -= 1;} 
    if (moveDown)             {speedY += 1;}
    speedY = max(-7.0, min(7.0, speedY));
    y += speedY;


  }

  void pressed(boolean up, boolean down) {

    if (up) {moveUp = true;}
    if (down) {moveDown = true;}

  }

  void released(boolean up, boolean down) {

    if (up) {moveUp = false;}
    if (down) {moveDown = false;}

  }

  //Collision help
  float top() {
    return y-h/2;
  }

  float bottom() {
    return y+h/2;
  }

  float left() {
    return x-w/2;
  }

  float right() {
    return x+w/2;
  }


}

Ответы [ 2 ]

1 голос
/ 20 февраля 2020

В приведенном ниже коде вы устанавливаете начало в true, когда клавиша нажата, и в false, когда нажатие завершено. Вы можете просто удалить строку, которая устанавливает начало в false, когда нажатие клавиши завершено, и мяч всегда будет двигаться, когда нажата пробел. нажал снова. Это можно сделать и в вашем методе keyPressed, переключая start вместо установки его в true. Что-то вроде if (key == ' '){start = !start;}

0 голосов
/ 20 февраля 2020

Ваша проблема в том, что когда вы отпускаете пробел, он устанавливает для поля start значение false. Затем, когда вызывается следующий метод draw(), он видит, что start==false и, следовательно, не перемещает шар.

Если вы удалите эту строку из метода keyReleased, тогда он должен работать правильно?

...