Main content
Computer programming - JavaScript and the web
Course: Computer programming - JavaScript and the web > Unit 4
Lesson 4: Making a side scroller: Hoppy BeaverBeaver character
Let's start by making our character, the hopping beaver. We'll use object-oriented design, discussed in this tutorial, to describe our Beaver character.
When creating a game character, we should think about what properties and behaviors it should have. For example, our beaver should keep track of her x and y position and how many sticks she has collected. She also needs two behaviors: hop, which makes her jump a little bit up, and fall, which makes her fall a bit down.
Here's what that could look like, as an object:
That program doesn't do a very good job at checking the different behaviors, though - it's not animated, so we can only see her in one state of being. Let's add a
draw
function, so that we can tell the beaver to do different things depending on user interaction. For this game, we want the beaver to hop whenever the user is pressing the space key. That can be implemented pretty simply:draw = function() {
background(255, 255, 255);
if (keyIsPressed && key.code === 32) {
beaver.hop();
} else {
beaver.fall();
}
beaver.draw();
};
That's pretty effective code, but if we ran it, we'd have to continuously press our space bar to keep the beaver from falling off the face of the canvas forever, never to return. We should constrain the y values to some reasonable value, to keep the beaver in screen. That's common in games, to keep characters inside the "game world." We could do that by using
constrain
in the draw function, passing it an appropriate min and max: this.y = constrain(this.y, 0, height-50);
Now, here's our program, with a keyboard-controlled hopping and falling beaver. Play around with it a bit!
Want to join the conversation?
- What if we had our own character draw out of shapes, then how would we get them to move and do actions on the screen? Would the coding be the same or would it be different because you couldn't use the images technique?
Sorry this was badly phrased but I just can't really explain it without droning on and on.(19 votes)- You can make a function then call that function.
This way, you treat the 'set' of your character (every command you use to draw him) as a single object, a single function, just like an 'image' command on KA.(20 votes)
- What is the need for constrain?(12 votes)
- When you're programming a game like this, constrain will help the character stay inside the game world by setting the max and min for the y position(when hopper goes up). So when you make hopper jump, he wont go up out of the screen of your game. Hope this helped!(28 votes)
- Why was the constrain function put in the
Beaver.prototype.draw
function? Could you have put in elsewhere and it would still have worked? Also, what are the 3 parameters in theconstrain
function and what do they do?(12 votes)- The
constrain
was put into that method because it is the only method that is run all the time. Any other method such ashop
orfall
wouldn't have worked in this case. As for the function itself, it takes a number and constrains it between two values. If the number is less than the lower bound or greater than the higher bound it is constrained.
But this is not the only way to do it. Instead of constantly constraining they
value within thedraw
method, use thehop
andfall
methods to keep the beaver in the screen. This can be done with themax
andmin
functions. They are like two halves of the constrain function, with themax
only limiting the upper bound, andmin
limiting the lower bound. Here is what it would look like.Beaver.prototype.hop = function() {
this.img = getImage("creatures/Hopper-Jumping");
this.y = max(this.y - 5, 0);
};
Beaver.prototype.fall = function() {
this.img = getImage("creatures/Hopper-Happy");
this.y = min(this.y + 5, height - 50);
};
Here are some links:
* https://www.khanacademy.org/computer-programming/constrainvalue-min-max/5870136103796736
* https://www.khanacademy.org/computer-programming/maxnum1-num2/4755409722146816
* https://www.khanacademy.org/computer-programming/minnum1-num2/4693347713155072
Good luck and happy coding!(13 votes)
- Why the construction function takes just two conditions (x,y) but it assigns 4 ?
var Beaver = function(x, y) {
this.x = x;
this.y = y;
this.img = getImage("creatures/Hopper-Happy");
this.sticks = 0;
};(4 votes)- This means that you can change the x and y whenever you call the function. It doesn't give you the option to change the image or the number of sticks when you call the function, because those are supposed to start a specific way and the programmer didn't have a desire to make them changeable.(9 votes)
- Hi! Beautiful work as always. I'm curious what the 'height' is in the constrain function. Is that the height of the object beaver? If so, how does it know -- from the saved image? Also, when 'hopping' hopper appears to torque clockwise 5-10 degrees. Why? I don't see any code explicitly directing that action. Thanks!(3 votes)
- The height is the height of the screen. In this case, the height is 400. You could technically put in "400-50", but it is good to use height because it is a global variable and will work for any height. It is like how mouseX and mouseY are variables that you don't have to define. You can also use width, which is also 400 in this case.
The reason Hopper appears to be moving is because when you press the spacebar button, the hopper image is replaced with the jumping hopper image. Here is the code:Beaver.prototype.hop = function() {
this.img = getImage("creatures/Hopper-Jumping");
this.y -= 5;
};
And later, it executed this inside the draw function:if (keyIsPressed && keyCode === 0) {
beaver.hop();(12 votes)
- Just to be sure,
var Beaver = function(x, y) {
this.x = x;
this.y = y;
this.img = getImage("creatures/Hopper-Happy");
this.sticks = 0;
};
Beaver.prototype.draw = function() {
image(this.img, this.x, this.y, 40, 40);
};
Beaver.prototype.hop = function() {
this.img = getImage("creatures/Hopper-Jumping");
this.y -= 5;
};
Beaver.prototype.fall = function() {
this.img = getImage("creatures/Hopper-Happy");
this.y += 5;
};
var beaver = new Beaver(10, 300);
beaver.draw();this.x
in this case meansbeaver.x
(same thing with all otherthis.y
,this.img
and so on), right??
if I'm wrong anthis
isn't like the way I think it is then can someone explain to me whatthis
does and an example of code which runs the same, one usingthis
and one not usingthis
.
(btw it would be super helpful if you could maybe explain some advanced words while answering the question when it comes to programming like methods or parameters. w
Words like those)(5 votes)- The beauty of Object-Oriented Programming (OOP) is that you can have interconnected functions. This interconnection can be very useful when we want to have multiple functions referencing the same thing. For instance, OOP allows you to link
draw
,hop
, andfall
methods toBeaver
.
Thethis
keyword references the "master object," allowing you to create or modify properties anywhere in its prototypes. You are correct thatthis.x
is essentially sayingbeaver.x
(for thebeaver
instance ofBeaver
).
Some term clarification, as requested. Objects can hold properties and methods. It's a method when it's a function. Thus, in your above code,draw
,hop
andfall
are methods, not properties.var obj = {
property1: 'hello, world',
property2: 10,
method: function(){}
};
Mozilla Developer Network has a lot of great HTML, CSS, and JS material. This MDN article may help:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
Parameters are function inputs. You define parameters when you make a function declaration by putting them in the parentheses:var cat = function(color, weight) {
// I defined 'color' and 'weight' as parameters above, allowing me to use them in my function
};
To pass arguments, you again place them in parentheses, this time when calling the function:cat('black', 12);
(5 votes)
- what is key.code === 32 ?(4 votes)
- It's the spacebar.(3 votes)
- How do you know what number is what key?
Say for instance:
draw = function() {
background(255, 255, 255);
if (keyIsPressed && key.code === 32) {
beaver.hop();
} else {
beaver.fall();
}
beaver.draw();
};
How did you know that the "space" bar is number 32?
Is is trial and error?(2 votes)- Why not (mostly) give up on
key.code
and usekey.toString()
instead. E.g.
is so much easier to read, and write.if (keyIsPressed && key.toString() === ' ') {
(5 votes)
- Why does the constrain function have "height - 50"? Also, what height are they referring to? I didn't see any variable named height.(2 votes)
- Hi Swara!
Theheight
variable is a premade variable. ProcessingJS creates it for you.
Its value is the height of the entire canvas.
You also havewidth
.
In this case, we don't want Hopper to fall all the way to the bottom of the canvas. We want her to stay 50 pixels above the edge.(5 votes)
- Where was I supposed to learn about key codes? I kind of get the idea, but it makes me worried it missed some important videos or something(2 votes)
- There is no video for key codes. You just have to look it up in the documentation. :)(4 votes)