【问题标题】:How can I change the direction of an object when it hits the edge of a wall according to the direction is headed?当物体撞击墙壁边缘时,如何根据方向改变物体的方向?
【发布时间】:2021-10-25 13:27:18
【问题描述】:

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

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;}
    
  }   
}
 

【问题讨论】:

  • 这是在导入什么库?
  • “库”是什么意思?
  • 您正在使用不属于 Java 且未在发布的代码中定义的东西;哪里来的?
  • 我正在使用一个名为“Processing”的平台,所以我在上面编写代码并使用 java 来制作它。

标签: java processing


【解决方案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);
           } 
       }
   } 

【讨论】:

  • 感谢您的帮助,非常感谢。这解决了我的问题。
【解决方案2】:

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

   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
   } 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多