We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello everyone! I need urgent help for my project. I need 10 rectangles at the bottom of the canvas, when I click them they should go up but they all should have different jumps. For example, rectangle1 jumps 10px while rectangle5 jumps 50, rectangle10 jumps 100px when I click on them. Appreciate your help!
Answers
Okay, so each rectangle is going to have a few properies that are different. For one, since they are all along the bottom of the screen, they are all going to have different X positions. But they all HAVE x positions! So we can start writing a class to define a Rectangle object with different starting X positions:
Now we need to be able to pass a different value in when we create one of these objects. So we will need a parameter for this in the constructor function. let's add that.
Now we can try creating some of these objects. We can store them easily in an array.
And we can create them with a loop:
Now you need to write some code... Your JumpingRect object needs a draw function! Where is it? Can you draw it there? You will also need to write a loop that draws all the objects in the jrects array... do this in draw().
Attempt this now. Once you have, you should a running sketch. Post this - or your attempt at it - for more help.
Once you have rectangles that have different X positions, you can give them OTHER different properties too... like... color... Or... HOW HIGH THEY JUMP...
Hello TfGuy44, Thank you for your quick answer! Unfortunately as a beginner I am struggling with those stuff. so I have some questions :) You've said "constructor function" do you mean setup draw() ? and should I add this to JumpingRect class or main code? do I need variables for location of the rectangles? If I do, where should I add it, to class or main code? Thanks a lot!!
A constructor function is a function without a return type that is inside a class, and has the same name as the class.
The constructor is what you call when you create a new instance of an object:
Your code should take the following format:
Attempt to fill in the blanks and POST THE ATTEMPT, PLEASE.
@pelibuu -- in order to make this approach work for you, you must use classes and objects. If you don't know what those are, start with the Objects Tutorial:
The awkward beginner way of doing the same thing without classes is to create a global variable for every property of each object. So instead of this:
You have this in your header:
Already with four rectangles you can see how messy the "simple" way gets! Imagine 16 rectangles, or 50! A class JumpingRect allows you to create a single object "r1" and it comes with a group of properties all built-in: r1.x, r1.y, r1.c, r1.jump ....