It seems so simple to me, but my solution doesn’t work. I’ve made a small program, my biggest and most advanced program, but still a small one. All it is is a ball that bounces off the floor and slowly runs out of energy. I’ve made it able to restart its bouncing by pressing SPACE and it can change direction by pressing the arrow keys, using a very simple velocity calculation(extremely simple actually).
Here’s my problem, I’m very new to programming, this is only my second day, and I need a way to bounce the ball off the side walls of the stage.
onClipEvent(load){
velocity = 0 //Vertical Velocity, is increased and decreased by the effects of gravity and bouncing with SPACE
sideVel =0 //Side Velocity, increases when the arrow keys are pressed, decreases over time
gravity = 2 //Gravity, constant force that never changes
}
onClipEvent(enterFrame){
_x += sideVel //Moves the ball the value of Side Velocity
if (Key.isDown(Key.LEFT)) {
sideVel -= 2 //Technically decreases Side Velocity, but really increases it in another direction
}
else {
if(sideVel<0) { //If the button isn't being pressed Side Velocity returns to 0 over time
sideVel += 1
}
}
if (Key.isDown(Key.RIGHT)) {
sideVel += 2 //Increases Side Velocity
}
else {
if(sideVel>0) //If the button isn't being pressed Side Velocity returns to 0 over time
sideVel -= 1
}
if (sideVel < -20){ //Side Velocity isn't allowed to go below this number
sideVel +=2 //So we add 2
}
if (sideVel > 20) { //Same as above
sideVel -=2
}
velocity += gravity //Regular Velocity increases by 2 every frame
_y += velocity //mcMain moves at the speed of its velocity
if(_y>=Stage.height){
if(Key.isDown(Key.SPACE)){
velocity=-28 //Sets Velocity to -28, pretty much the same as doing a jump
}
else {
_y = Stage.height
velocity *= -0.9 //Reverses mcMain's velocity, so it bounces back into the air at a slightly slower speed
}
/*Here's the problem
if(_x>=Stage.width - 25){
_x=Stage.width - 25
sideVel *= -1
}
if(_x<=Stage.width - 550){
_x=Stage.width - 550
sideVel *= -1
}
}
}
You have to manually change the position of the MC (
MC.x++and whatnot) when it hits the wall so that the collision doesn’t register multiple times. Also, usingwhilestatements in place ofiffor the wall collisions will ensure that the ball doesn’t pass through the wall.