Cómo iniciar a continuación el movimiento de parada

Josías Parrott:

Mi código se detiene un cuadrado rojo cuando toca un cuadrado azul, pero no quiero que el cuadrado rojo para detener indefinidamente. ¿Cómo puedo arreglar eso?

He creado la detección de colisiones, y hace que la velocidad = 0 si el cuadrado rojo toca el cuadrado azul.

//r=red
float rx = 200;
float ry = 375;
float rw = 50;
float rh = 50;

//b=blue
float bx = 550;
float by = 375;
float bw = 50;
float bh = 50;

float speed = 2;
//float cspeed = 2;

void setup() {
  size(800, 800);
  noStroke();
  noSmooth();
  noCursor();
}

void draw() {
  surface.setTitle(mouseX + ", " + mouseY);
  background(50);
  collision();
  move();
  display();
}

void collision() {
  //Check if blue and red are touching
  boolean hit = rectRect(rx, ry, rw, rh, bx, by, bw, bh);
  if (hit) {
    speed = 0;
  } else {
    speed = 2;
  }
}

void display() {

  fill(0, 0, 255);  //Blue square
  rect(bx, by, bw, bh);

  fill(255, 0, 0);  //Red square
  rect(rx, ry, rw, rh);
}



void move() {
  //Red square movement
  if (keyPressed) {
    if (key == 'd' || key == 'D') {
      rx = rx + speed;
      if (rx > width) {
      }
    }
  }


  if (keyPressed) {
    if (key == 'a' || key == 'A') {
      rx = rx - speed;
      if (rx > width) {
      }
    }
  }

  if (keyPressed) {
    if (key == 'w' || key == 'W') {
      ry = ry - speed;
      if (ry > width) {
      }
    }
  }

  if (keyPressed) {
    if (key == 's' || key == 'S') {
      ry = ry + speed;
      if (ry > width) {
      }
    }
  }
}




boolean rectRect(float rx, float ry, float rw, float rh, float bx, float by, float bw, float bh) {

  //is red touching blue?

  if (rx + rw >= bx && 
    rx <= bx + bw &&   
    ry + rh >= by &&    
    ry <= by + bh) { 
    return true;
  }
  return false;
}

No quiero que el cuadrado rojo y el cuadrado azul a la superposición, pero yo quiero seguir jugando si lo hacen contacto. En este momento el cuadrado rojo se detiene indefinidamente.

laancelot:

En void collision()configura que la velocidad de la plaza bajará a 0,01 cuando se produce una colisión.

Comprobar si hay colisión después de su plaza se movió .

Una vez que sus plazas choca, no pueden moverse más, por lo que la velocidad se ha quedado atascado en 0,01. Siempre.

Hay muchas maneras en que puede resolver esto. Desde el cuadrado azul nunca se mueven, se puede comprobar por la colisión de un movimiento antes de que se superponen, o "rebotar" el cuadrado rojo cuando se produce una colisión.

Una solución rápida / fácil sería modificar esta función:

void move() {
  //Red square movement
  // You only need to check for input once, then for which input interests you
  if (keyPressed) {
    // I think this would look better in a switch statement, but we'll keep it an If for simplicity
    if (key == 'd' || key == 'D') {
      // checking if the square will collide BEFORE it does
      // notice that the square won't move if it detects that this move will be a collision
      if (!rectRect(rx + speed, ry, rw, rh, bx, by, bw, bh)) {
        rx = rx + speed;
      }
    }
    else if (key == 'a' || key == 'A') {
      if (!rectRect(rx - speed, ry, rw, rh, bx, by, bw, bh)) {
        rx = rx - speed;
      }
    }
    else if (key == 'w' || key == 'W') {
      if (!rectRect(rx, ry - speed, rw, rh, bx, by, bw, bh)) {
        ry = ry - speed;
      }
    }
    else if (key == 's' || key == 'S') {
      if (!rectRect(rx, ry + speed, rw, rh, bx, by, bw, bh)) {
        ry = ry + speed;
      }
    }

    if (ry > width) {
      // insert whatever you were planning with this condition
    }
  }
}

Ahora, void collision()ha sido tomado por void move(), por lo que se puede borrar void collision. Es, literalmente, no sucederá, porque dejamos la plaza antes de cualquier colisión puede suceder.



Ahora ... que desea agregar algunos más cuadrados. Fácil.

Claro, usted puede escribir una movefunción para cada plaza. Pero esto es agotador, y seguro que tiene que haber una mejor manera.

Existe, pero esto pondrá a prueba sus habilidades. Vamos a mantener las cosas simples para evitar abrumar la derecha del palo, pero sabemos que vamos a enhebrar en territorio POO (Programación Orientada a Objetos). Si estás en la escuela, se beneficiará mucho de la clase comprensión (bueno, incluso si no estás en clase de la escuela son todavía impresionante).

En primer lugar, vamos a escribir una clase simple que podemos utilizar para crear y administrar los rectángulos formas se utiliza en este programa. Si está utilizando el IDE de procesamiento, sugiero crear una "Nueva pestaña" por lo que mantenemos la ordenada código. No es absolutamente necesario, ya que el compilador no verá la diferencia, pero a medida que el proyecto se convierta en pestañas más complejos son una gran herramienta para organizar el código.

En su nueva pestaña, introduzca el código:

class Rectangle {
  // This should be 'private', but I'm using 'protected' in case I wan to inherit those later, and 'public' to keep things simple
  public float x = 0;
  public float y = 0;
  public float w = 50;
  public float h = 50;
  protected boolean isVisible = true;
  protected color fillColor;

  // This is the constructor. It serves to initialize the class.
  public Rectangle(float xx, float yy, float ww, float hh, color cc) {
    x = xx;
    y = yy;
    w = ww;
    h = hh;
    fillColor = cc;
  }

  public void Render() {
    // I like to let my class draw themselves!
    if (isVisible) {
      fill(fillColor);
      rect(x, y, w, h);
    }
  }

  public void Move(float moveX, float moveY) {
    // This will be used to move. Since the variables are 'protected', they cannot be accessed from outside this class, so I have to create a tool to use them.
    // It is good practice to set 'public' only what's needed, and to manage class variables inside the class.
    // This is for many good reasons. Among those, remember that it's harder to debug 'why is my x position weird' when it can be accessed from anywhere.
    x += moveX;
    y += moveY;
  }

  public boolean Collision(float xx, float yy, float ww, float hh, float moveX, float moveY) {
    // Give coordinates to this function and it will tell you if there's a collision with this rectangle
    return Intersect(x + moveX, y + moveY, w, h, xx, yy, ww, hh);
  }
}

¿Hecho? ¡Excelente! Ahora usted tiene una clase rectángulo que contendrá cosas como coordenadas, color, etc. de los rectángulos.

Ahora vamos a tener que hacer un par de cambios en el código.

En primer lugar, no es necesario realizar un seguimiento de las variables globales a las posiciones del cuadrado rojo y azul, ya que esto será tratado por la clase que acaba de crear. Puede borrar los. Las variables globales son útiles, pero como regla general, cuanto menos se utilizan mejor te va a ir, como variables globales pueden llegar a ser una pesadilla para rastrear y provocar errores imprevistos.

A continuación, tendrá que inicializar su nueva clase en un par de agradables rectángulos. Para mantener las cosas ordenadas, tendremos un rectángulo llamado 'rojo', y un ArrayList de rectángulos sin nombre que serán los obstáculos. ArrayLists son una gran herramienta que puede aprender a utilizar más adelante; por ahora vamos a decir que va a contener todos esos obstáculos en una lista ordenada, que vamos a recurrir cuando sea necesario.

La movefunción tendrá que hacer frente a todos los nuevos obstáculos y también con el hecho de que nos ocupamos de un objeto y no un montón de variables globales.

Y, por último, la función rectRect tendrá que ser actualizado. Por ahora, se utiliza para comprobar si el rojo y el azul se cruza, pero a partir de ahora tiene que ser capaz de verificar esto para cualquier y todos los rectángulos. Lo haremos más neutral y lo usamos de manera diferente.

Aquí está el código después de esos cambios:

//red
Rectangle red;

//all other rectangles
ArrayList <Rectangle> rectList;

float speed = 2;
//float cspeed = 2;

void setup() {
  size(800, 800);
  noStroke();
  noSmooth();
  noCursor();

  // Initializing Red square
  red = new Rectangle(200, 375, 50, 50, color(255, 0, 0));
  // Initializing a bunch of rectangles
  rectList = new ArrayList <Rectangle>();
  rectList.add(new Rectangle(550, 375, 50, 50, color(0, 0, 255)));  // Red
  rectList.add(new Rectangle(300, 500, 50, 50, color(0, 255, 0)));  // Green
  // you can add as many as you want
}

void draw() {
  surface.setTitle(mouseX + ", " + mouseY);
  background(50);
  move();
  display();
}

void display() {
  red.Render();

  // this is a java 'For Each' loop. Research it, it's very useful.
  for ( Rectangle r : rectList) {
    r.Render();
  }
}

void move() {
  //Red square movement
  float moveX = 0;
  float moveY = 0;

  if (keyPressed) {
    // We're going calculate up how much we want to move the red square first
    // Then we'll check for collisions
    // Then we'll move the square (it there are no collisions)
    if (key == 'd' || key == 'D') {moveX += speed;}
    else if (key == 'a' || key == 'A') {moveX -= speed;}
    else if (key == 'w' || key == 'W') {moveY -= speed;}
    else if (key == 's' || key == 'S') {moveY += speed;}

    for (Rectangle r : rectList) {
      if (red.Collision(r.x, r.y, r.w, r.h, moveX, moveY)) {
        // If a collision is detected, we exit this function so there will be no move
        return;
      }      
    }

    red.Move(moveX, moveY);
  }
}

// INTERSECT RECTs
// The old function was nice, but it was really useful only with your specific example. You can re-use this one with any set of rectangles.
// There are many ways to write this function. I wrote this instance back when I was a student, and I still use it to this day.
boolean Intersect(float x1, float y1, float w1, float h1, float x2, float y2, float w2, float h2)
{
  boolean checkX = false;
  boolean checkY = false;

  if ( (x1<=x2 && (x1+w1)>=x2) || (x1<=(x2+w2) && (x1+w1)>=x2+w2) || (x1>=x2 && (x1+w1)<=(x2+w2)) ) {checkX = true;}
  if ( (y1<=y2 && (y1+h1)>=y2) || (y1<=(y2+h2) && (y1+h1)>=y2+h2) || (y1>=y2 && (y1+h1)<=(y2+h2)) ) {checkY = true;}

  if (checkX && checkY) {return true;}

  return false;
}

Ahora se puede añadir un montón de otros cuadrados y rectángulos de cualquier y todos los tamaños y colores! ¡Intentalo! Pero, más importante aún, tratar de entenderlo. Si tiene alguna pregunta, recuerda que yo estoy aquí para ayudar.

¡Que te diviertas!

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=313631&siteId=1
Recomendado
Clasificación