我想编写一个对象,该对象在移动时碰到程序的边缘时会产生脉冲效应.因此,当碰到边缘时,对象应该变得更大一点,然后一遍又一遍地转到输出大小.我已经花了几个小时寻找问题,但找不到答案.有小费吗?
我的代码:
float ballsizeX = 60;
float ballsizeY = 60;
float ballX = 0;
float ballY = 0;
float speedX = 2;
float speedY = 2;
void setup() {
size(500, 400);
}
void draw() {
background(255);
fill(random(255), 255, random(255));
ellipse(ballX, ballY, ballsizeX, ballsizeY);
speedX = speedX * 1;
speedY = speedY * 1;
ballX = ballX + speedX;
ballY = ballY + speedY;
if (ballX < 0 || ballX > 500) {
speedX = speedX * (-1);
} else if (ballY < 0 || ballY > 400) {
speedY = speedY * (-1);
}
else if(ballsizeX>60||ballsizeY>60){
ballsizeX = ballsizeX * (-1);
ballsizeY = ballsizeY * (-1);
}
else if(ballsizeX<30||ballsizeY<30){
ballsizeX = ballsizeX + 1;
ballsizeY = ballsizeY + 1;
}
}
解决方法:
在初始状态下,ballsizeX为60,ballsizeY为.
既不满足条件ballsizeX> 60 || ballsizeY> 60,也不满足条件ballsizeX< 30 || ballsizeY< 30.
由于两个值都不会更改(条件覆盖的代码块中除外),因此条件将永远不会满足.
如果球碰到墙,则增加球的大小:
if (ballX < 0 || ballX > 500) {
speedX = speedX * (-1);
ballsizeY = initSize*2;
} else if (ballY < 0 || ballY > 400) {
speedY = speedY * (-1);
ballsizeX = initSize*2;
}
只要比初始尺寸要大,就可以减小每一帧中的球的尺寸:
if ( ballsizeX > 30 ) {
ballsizeX = ballsizeX - 1;
}
if ( ballsizeY > 30 ) {
ballsizeY = ballsizeY - 1;
}
请参见示例,其中我将建议应用于原始代码:
float initSize = 30;
float ballsizeX = initSize;
float ballsizeY = initSize;
float ballX = initSize/2;
float ballY = initSize/2;
float speedX = 2;
float speedY = 2;
void setup() {
size(500, 400);
}
void draw() {
background(255);
fill(random(255), 255, random(255));
ellipse(ballX, ballY, ballsizeX, ballsizeY);
speedX = speedX * 1;
speedY = speedY * 1;
ballX = ballX + speedX;
ballY = ballY + speedY;
if ( ballsizeX > initSize ) {
ballsizeX = ballsizeX - 1;
}
if ( ballsizeY > initSize ) {
ballsizeY = ballsizeY - 1;
}
if (ballX < initSize/2 || ballX > width-initSize/2) {
speedX = speedX * (-1);
ballsizeY = 60;
} else if (ballY < initSize/2 || ballY > height-initSize/2) {
speedY = speedY * (-1);
ballsizeX = 60;
}
}