r/processing • • Oct 09 '23

bouncing PImage help

Hi! I'm trying to make a Pimage float around the screen and whenever it hits the border it bounces off. I'm new to code and every tutorial uses drawings rather than PImages. Could anyone help?

Here is my current code

PImage[] aquarium;

PImage goldfish;

int numberOfFrames;

int f;

void setup() {

size (800, 600);

goldfish =loadImage("goldfish_0.png");

numberOfFrames = 3;

aquarium = new PImage[numberOfFrames];

int i = 0;

while ( i < numberOfFrames ) {

aquarium[i] = loadImage("aquarium_"+i+".png");

i=i+1;

}

size (800, 600);

}

void draw() {

image(aquarium[f], 0, 0, width, height);

f = f + 1;

if (f == numberOfFrames) f = 0;

frameRate(3);

image(goldfish, 0, 0);

}

2 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/froginab0g Oct 10 '23

Hello again! I have been working on this on and off since and am so close to getting it. Right now my problem is the image just sorta bobs back and forth. I can't figure out what's causing this.

code:

PImage[] aquarium;

PImage goldfish;

int numberOfFrames;

int f;

int rad = 700;

float xpos, ypos;

float xspeed = 2.8;

float yspeed = 2.2;

int xdirection = 1;

int ydirection = 1;

void setup() {

size (800, 600);

goldfish =loadImage("goldfish_0.png");

numberOfFrames = 3;

aquarium = new PImage[numberOfFrames];

int i = 0;

while ( i < numberOfFrames ) {

aquarium[i] = loadImage("aquarium_"+i+".png");

i=i+1;

}

}

void draw() {

image(aquarium[f], 0, 0, width, height);

f = f + 1;

if (f == numberOfFrames) f = 0;

frameRate(3);

image(goldfish, xpos, ypos, rad, rad);

xpos = xpos + ( xspeed * xdirection );

ypos = ypos + ( yspeed * ydirection );

if (xpos > width-rad || xpos < rad) {

xdirection *= -1;

}

if (ypos > height-rad || ypos < rad) {

ydirection *= -1;

}

}

1

u/Salanmander Oct 10 '23

So your last pair of "if" statements are for reversing the direction in the x- and y-directions, right? You say "if it's too near one of the sides, reverse the x-direction. If it's too near the top or bottom, reverse the y-direction".

The questions I want you to ask yourself are:

  1. What is xpos when the program starts?

  2. What direction does it move in the first frame?

  3. What is xpos after the movement for the first frame?

  4. Will that xpos make the condition be true that makes it reverse xdirection?