【问题标题】:How to change the direction of a moving picture once it hits the corner of the screen如何改变运动画面的方向,一旦它碰到屏幕的角落
【发布时间】:2021-10-24 21:34:53
【问题描述】:

我拥有的图像是一个右上角的箭头,我希望它在与屏幕的角或边缘发生碰撞时改变方向,这样我的箭头图片就可以朝向它前进的方向。

int x;
int y;
int xspeed;
int yspeed;
PImage dvd;

void setup() {
  size(800, 600);
  x = 400;
  y = 100;
  dvd = loadImage("topright.png");
  xspeed = 10;
  yspeed = 10;
}

void draw() {
  background(50);
  image(dvd, x, y, 80, 60);
  x = x + xspeed;
  y = y + yspeed;
  if (x + 80 == width || x == 0) {
    xspeed = xspeed * -1;
  }
  if (y + 60 == height || y == 0) {
    yspeed = -yspeed;
  }
}

【问题讨论】:

  • 你还有其他预画的图标吗?
  • 我会考虑改用类似if (x + 80 >= width || x == 0) { 的东西

标签: java image processing collision


【解决方案1】:

您可以通过使用scale() 缩放几何来实现您想要的。这个想法是根据移动方向使用 (1, 1)、(-1, 1)、(1, -1) 或 (-1, -1) 进行缩放。首先translate() (-40, -40) 的图像。现在 (0, 0) 位于图像的中心。之后翻转 (scale) 图像。最后translate把图片放到它的traget位置:

int x;
int y;
int xspeed;
int yspeed;
int scale_x = 1;
int scale_y = 1;
PImage dvd;

void setup() {
  size(800, 600);
  x = 400;
  y = 100;
  dvd = loadImage("topright.png");
  xspeed = 10;
  yspeed = 10;
}

void draw() {
  background(50);
  
  pushMatrix();
  translate(x+40, y+40);
  scale(scale_x, scale_y);
  translate(-40, -40);
  image(dvd, 0, 0, 80, 60);
  popMatrix();
  
  x = x + xspeed;
  y = y + yspeed;
  if (x + 80 >= width) {
    xspeed *= -1;
    scale_x = -1;
  }
  else if (x <= 0) {
    xspeed *= -1;
    scale_x = 1;
  }
  if (y + 60 >= height) {
    yspeed *= -1;
    scale_y = -1;
  } else if (y + 60 == height || y == 0) {
    yspeed *= -1;
    scale_y = 1;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多