Wall Bounce

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

[lua]---->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 ); [import]uid: 106825 topic_id: 19100 reply_id: 319100[/import]

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;

[lua]---->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 )[/lua]

Peach :slight_smile: [import]uid: 52491 topic_id: 19100 reply_id: 73675[/import]