【Processing】円や画像をウィンドウの端で跳ね返らせる

プログラミング

こんにちは、コンスキです。

今回はProcessingを使った、図形や画像をウィンドウの端で跳ね返らせるアニメーションのスクリプトをご紹介します。

完成イメージ

完成するとこんな感じのアニメーションになります。

– 円の場合 –

-画像の場合-

スクリプト

int window_width = 600;
int window_height = 400;
int width = 100;
int height = 100;
int x_radius = width / 2;
int y_radius = height / 2;
int x = 300;
int y = 200;
int x_increment = 3;
int y_increment = 3;

void settings() {
  size(window_width, window_height);
}

void draw() {
  background(0);
  ellipse(x, y, width, height);
  if(x + x_increment > window_width - x_radius) { x_increment = - x_increment; }
  if(y + y_increment > window_height - y_radius) { y_increment = - y_increment; }
  if(x + x_increment < x_radius) { x_increment = - x_increment; }
  if(y + y_increment < y_radius) { y_increment = - y_increment; }
  x =  x + x_increment;
  y =  y + y_increment;  
}

画像

PImage img;
int x = 300;
int y = 200;
int width = 128;
int height = 100;
int x_increment = 3;
int y_increment = 3; 
int window_width = 600;
int window_height = 400;

void settings() {
  size(window_width, window_height);
}

void setup() {
  img = loadImage("https://konsuki.com/wp-content/uploads/2021/10/favicon.png");
  img.resize(width, height);
}


void draw() {
  background(0);
  image(img, x, y);
  if(x + x_increment > window_width - width) { x_increment = - x_increment; }
  if(y + y_increment > window_height - height) { y_increment = - y_increment; }
  if(x + x_increment < 0) { x_increment = - x_increment; }
  if(y + y_increment < 0) { y_increment = - y_increment; }
  x =  x + x_increment;
  y =  y + y_increment;  
}

さいごに

円や画像の跳ね返りのアニメーションをよく使うため、メモとして残しておきました。

コピペして活用してください。

コメント

  1. […] 【Processing】円や画像をウィンドウの端で跳ね返らせるこんにちは、コンス… […]

タイトルとURLをコピーしました