当物体撞到墙的边缘时,如何根据朝向的方向改变物体的方向?

How can I change the direction of an object when it hits the edge of a wall according to the direction is headed?

我做了一个可以从边缘反弹的箭头,但我希望箭头在被击中后根据它的前进方向改变方向。例如,如果箭头向下,当它击中右墙时,它需要改变方向,因为它朝向底墙,然后向上反弹。当物体弹开并朝不同的方向前进时,我希望箭头的图像相应地发生变化,以便显示前进的方向,这将是箭头向右下方时右下角箭头的图像,并且每个方向依此类推。

int xspeed;
int yspeed;

Arrows bob;

int x=50, y=50;

void setup()
{
 size(700, 700); 
  bob = new Arrows(30, 350);

}


void draw()
{
 background(255);
 bob.update();
 
 x = x+xspeed;
 y = y+yspeed;
  
}
class Arrows {
  int x;
  int y;
  int dx;
  int dy;
  int speedX = 4;
  int speedY = 4;
  PImage image1, image2, image3, image4;
  
  //constructor
  Arrows(int x, int y)
  {
   this.x = x;
   this.y = y;
   image1 = loadImage("Arrow1.png");
   image2 = loadImage("Arrow2.png");
   image3 = loadImage("Arrow3.png");
   image4 = loadImage("Arrow4.png");
    
  }
  
  void update()
  {
   render();
   move();
  }
  
  void render()
  {
   image(image1, this.x, this.y); 
  }
  
  void move()
  {
    
   x +=speedX; 
   y +=speedY; 
   
   if(x<0||x>(width-50))
   { speedX *=-1;}
   
   if(y<0||y>(height-50))
   { speedY *=-1;}
    
  }   
}
 

根据方向绘制图像即可

Arrows(int x, int y) {
    // [...]

   void render() {
       if (speedY > 0) {
           if (speddX > 0) {
               image(image3, this.x, this.y); 
           } else {
               image(image4, this.x, this.y);
           } 
       else {
           if (speddX > 0) {
               image(image1, this.x, this.y); 
           } else {
               image(image2, this.x, this.y);
           } 
       }
   } 

另一种只使用一张图像的方法是利用处理的能力来影响绘图矩阵(改变处理绘制的方向和原点)。

   void render() {
       pushMatrix(); // store current matrix
       translate(this.x, this.y); // change drawing matrix origin to image coords
       if (speedY > 0) {
           if (speedX> 0) {
                // rotate drawing matrix in right direction
                rotate(radians(0));
           } else {
                rotate(radians(90));
           } 
       else {
           if (speedX> 0) {
                rotate(radians(180));
           } else {
               rotate(radians(270));
           } 
       }
       image(arrow, 0, 0); // draws the rotated angle at new 'origin'
       popMatrix(); // undo translate/rotate, return to previous drawing matrix
   } 

当您复制并粘贴此代码时,输​​入度数可能不起作用。这是因为在每种情况下都必须根据图像指向的原始方向旋转图像。(您还可以保存调用以针对图像指向的原始方向进行旋转)。