If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Beaver 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?

  • blobby blue style avatar for user Sophie
    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)
    Default Khan Academy avatar avatar for user
  • mr pink red style avatar for user sandramaryjacob27
    What is the need for constrain?
    (12 votes)
    Default Khan Academy avatar avatar for user
  • hopper jumping style avatar for user Looch
    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 the constrain function and what do they do?
    (12 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user tadeu
    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;
    };
    (5 votes)
    Default Khan Academy avatar avatar for user
    • leaf blue style avatar for user Bjørn
      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)
  • leaf green style avatar for user Boyer.Andrew.7
    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)
    Default Khan Academy avatar avatar for user
    • primosaur seedling style avatar for user *nat  ☀ ☁ ☂ ☃
      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)
  • piceratops seedling style avatar for user Logixz
    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 means beaver.x (same thing with all other this.y, this.img and so on), right??

    if I'm wrong an this isn't like the way I think it is then can someone explain to me what this does and an example of code which runs the same, one using this and one not using this.

    (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)
    Default Khan Academy avatar avatar for user
    • male robot donald style avatar for user JavaLava
      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, and fall methods to Beaver.
      The this keyword references the "master object," allowing you to create or modify properties anywhere in its prototypes. You are correct that this.x is essentially saying beaver.x (for the beaver instance of Beaver).
      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 and fall 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)
  • winston default style avatar for user Ⓙⓞⓔ 🥳
    what is key.code === 32 ?
    (4 votes)
    Default Khan Academy avatar avatar for user
  • starky ultimate style avatar for user Swara Patil
    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)
    Default Khan Academy avatar avatar for user
    • spunky sam blue style avatar for user Dalendrion
      Hi Swara!

      The height variable is a premade variable. ProcessingJS creates it for you.
      Its value is the height of the entire canvas.
      You also have width.

      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)
  • purple pi purple style avatar for user LukeNape
    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)
    Default Khan Academy avatar avatar for user
  • blobby blue style avatar for user Anjali Rajesh
    How do you know what key matches the number? For example, how would you know if 32 was space? Are there any other numbers you could use?
    (2 votes)
    Default Khan Academy avatar avatar for user