Wall Bounce

I would like object "Berry" to bounce off the edges of the screen. Where am I going wrong with this function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
---->Bounce off walls
xspeed, yspeed = math.random(-3,3), math.random(-3,3)
function animate(event)
        berry.x = berry.x + (xspeed)
        berry.y = berry.y + (yspeed)
        if(berry.x < 1) then --left wall
             berry.x = berry.x + xspeed 
             xSpeed = -xSpeed 
        end
        if(berry.x > display.contentWidth-1)  then --right wall
            berry.x = berry.x - xspeed 
            xSpeed = -xSpeed 
        end
        if(berry.y > display.contentHeight-1)  then --floor
            berry.y = berry.y - yspeed 
            ySpeed = -ySpeed 
        end
        if(berry.y < 1)  then --ceiling
            berry.y = berry.y + yspeed 
            ySpeed = -ySpeed 
        end
end
Runtime:addEventListener( "enterFrame", animate );

Try something like this, although you may want to adjust the left and top wall to line up with the starting speed - I just threw this together from your original code to give you an idea;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
---->Bounce off walls
xspeed, yspeed = math.random(-3,3), math.random(-3,3)
function animate(event)
        berry.x = berry.x + (xspeed)
        berry.y = berry.y + (yspeed)
        if(berry.x < 1) then --left wall
             berry.x = berry.x + xspeed*2
             xspeed = 3
        end
        if(berry.x > display.contentWidth-1)  then --right wall
            berry.x = berry.x - xspeed*2 
            xspeed = -xspeed
        end
        if(berry.y > display.contentHeight-1)  then --floor
            berry.y = berry.y - yspeed*2
            yspeed = -yspeed
        end
        if(berry.y < 1)  then --ceiling
            berry.y = berry.y + yspeed*2 
            yspeed = 3
        end
end
Runtime:addEventListener( "enterFrame", animate )
views:1525 update:2011/12/30 9:10:41
corona forums © 2003-2011