Make a sprite bounce back and forth question

So I have a student who really wants to make a sprite move up to the top of the screen then when they get the stop move down until they reach the bottom and then go back up. Basically bouncing up and down on the screen.

Neither of us can figure out a way to make this happen. Anyone have any thoughts. Here is my code that I remixed so I can play around with it.

Hi Ben,

There are several ways to make this happen. In this unit, Chapter 2 Building Games will provide the student with the code needed to cause this to happen. My suggestion is to have the student work through these lessons and then return to Lesson 14 to update their project.

Do you have a link to where Ch. 2 Building Games is?

This being an old post, I can only think that she was referring to what is now Unit 3 of Computer Science Discoveries. Here’s a link to the lesson where complex sprite movement is taught. This is what can be used to create the effect referred to earlier in this post.

Complex Sprite Movement

Good luck!

Mike

Great thanks so much. I eventually figured it out. I appreciate you taking the time to reply. I got it to look like it is bouncing:

if (sprite.y > 350) {
    sprite.velocityY=-45;
}
else  {
    sprite.velocityY=sprite.velocityY+3;
}

I also got it to go back and forth by checking two boolean expressions:

  if (sun.x > 375 && sun.velocityX == 3) { //checks for a positive direction
    sun.velocityX = -3; //Change the direction to negative.
  }
  else if (sun.x <50 && sun.velocityX == -3) { //checks for a negative direction
    sun.velocityX = 3; //Change the direction to positive.
  }

There are lots of other ways to do this as well, I found.

Blessings,

Timothy

1 Like