I know the cord that moves the ball, but I don't know how to bounce it back.
Thank you for your help.
Below is the code to move the ball.
float x;
int velocityX=1;
void setup() {
size (400,300);
x = 0;
}
void draw() {
background(0);
x+ = velocityX;
fill(255,255,50);
else (x, height / 2, 20, 20);
}
First of all, I would like to point out that I cannot speak Japanese.This is my first answer.I used Google translation, so please apologize if I accidentally informed someone.:)
You need to check if the ball hit the wall (left or right).If hit, change the speed from positive (increase) to negative (decrease).
The code requires the following elements:
- If State
- or the logical operator
- Multiplication operator
Translate the above words into pseudocode:
If the x position of the ball is greater than the right wall (sketch width) or the x position of the ball is less than the left wall (0), the speed must reverse the sign (positive to negative, and vice versa).
Convert pseudocode to code:
// If the ball's x position is greater than the right or left wall (0)
if(x>width||x<0){
// Inverted direction (speed) (+1*-1=-1, -1*-1=+1)
velocityX=velocityX*-1;
}
velocityX=velocityX*-1;
Write more concisely
velocityX*=-1;
Add the above to the code.
float x;
int velocityX=1;
void setup() {
size (400,300);
x = 0;
}
void draw() {
background(0);
x+ = velocityX;
if(x>width||x<0){
velocityX*=-1;
}
fill(255,255,50);
else (x, height / 2, 20, 20);
}
Closing remarks:
- I recommend that you format the code in an orderly fashion (Ctrl+T/CMD+T): It is easy to read and, on average, spends more time reading than writing the code.
- Be sure to check the processing tutorial: bound, Boundball
- Watch Daniel Shiffman's YouTube video.In English, I hope the Closed Captioning (CC) > Automatic Translation > Japanese option will help.The translation is not perfect, but a visual explanation would make sense if it worked.
© 2024 OneMinuteCode. All rights reserved.