google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hướng dẫn tạo trò chơi RPG đơn giản với JavaScript và Crafty Bạn đang chán ngấy các trò chơi JavaScript và muốn thử tìm hiểu cách thức xây dựng các trò chơi trên nền web? Thì bài viết hướng dẫn sử dụng JavaScript này là một nguồn tham khảo đáng giá dành cho bạn.

Bài viết này hướng dẫn chúng ta sử dụng một thư viện JavaScript là Crafty để tạo ra một trò chơi nhập vai RPG đơn giản nhưng đồ họa khá đẹp cùng với cách chơi cũng không quá đơn giản để tạo sự nhàm chán. Cơ bản, chúng ta cần làm những việc cần thiết như: định hình các nhân vật, xây dựng các cảnh chơi, xây dựng lối chơi (gameplay), tạo các hoạt hóa và kết hợp chúng thành một thể thống nhất.

Trang trong sẽ cung cấp cho bạn bài viết chi tiết cùng với hướng dẫn, cũng như là trò chơi mẫu để bạn thử cùng với mã nguồn đầy đủ cho phép bạn tải về.


Nhãn: tạo trò chơi, trò chơi RPG, trò chơi trên nền web, trò chơi nhập vai RPG, đồ họa, nhân vật

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

Sprites

view the demo | download demo

Remember that sprite map from earlier? It’s time to use that in the game and get some visuals here. Crafty has an inbuilt method to splice sprite maps into individual components that can be applied to any 2D entity.

window.onload = function() {
  // Start crafty

  Crafty.init(50, 400, 320);
  Crafty.canvas();

  // Turn the sprite map into usable components
  Crafty.sprite(16, "sprite.png", {

    grass1: [0,0],
    grass2: [1,0],

    grass3: [2,0],
    grass4: [3,0],

    flower: [0,1],
    bush1:  [0,2],

    bush2:  [1,2],
    player: [0,3]

  });

  // The loading screen that will display while our assets load
  Crafty.scene("loading", function() {

    // Load takes an array of assets and a callback when complete
    Crafty.load(["sprite.png"], function() {

      Crafty.scene("main"); //when everything is loaded, run the main scene
    });
    
    // Black background with some loading text
    Crafty.background("#000");

    Crafty.e("2D, DOM, text").attr({w: 100, h: 20, x: 150, y: 120})

      .text("Loading")
      .css({"text-align": "center"});

  });
  
  // Automatically play the loading scene
  Crafty.scene("loading");
};

The first argument is the tile size (in our case is 16 pixels by 16 pixels). This defaults to 1 if left out. The next argument is the path to the sprite map. Finally the last argument is an object where the key is the label and the value is an array for where the particular sprite is located in the image.

The values are multiplied by 16 so you need only give the amount of tiles from the top left. If a sprite takes up a width or height greater than one tile, simply add it to the array following this format:

[x, y, w, h]

You may notice that not all of the sprites in the sprite map have been labelled. This is because the sprites form an animation which we will add later.

window.onload = function() {
  // Start crafty

  Crafty.init(50, 400, 320);
  Crafty.canvas();

  // Turn the sprite map into usable components
  Crafty.sprite(16, "sprite.png", {

    grass1: [0,0],
    grass2: [1,0],

    grass3: [2,0],
    grass4: [3,0],

    flower: [0,1],
    bush1:  [0,2],

    bush2:  [1,2],
    player: [0,3]

  });

  // Method to randomy generate the map
  function generateWorld() {
    // Generate the grass along the x-axis

    for (var i = 0; i < 25; i++) {

      // Generate the grass along the y-axis
      for (var j = 0; j < 20; j++) {

        grassType = Crafty.randRange(1, 4);
        Crafty.e("2D, canvas, grass" + grassType)

          .attr({x: i * 16, y: j * 16});

        // 1/50 chance of drawing a flower and only within the bushes
        if (i > 0 && i < 24 && j > 0 && j < 19 && Crafty.randRange(0, 50) > 49) {

          Crafty.e("2D, DOM, flower, animate")
            .attr({x: i * 16, y: j * 16})

            .animate("wind", 0, 1, 3)
            .bind("enterframe", function() {

              if (!this.isPlaying())
                this.animate("wind", 80);

            });
        }
      }
    }

    // Create the bushes along the x-axis which will form the boundaries
    for (var i = 0; i < 25; i++) {

      Crafty.e("2D, canvas, wall_top, bush"+Crafty.randRange(1,2))
        .attr({x: i * 16, y: 0, z: 2});

      Crafty.e("2D, canvas, wall_bottom, bush"+Crafty.randRange(1,2))
        .attr({x: i * 16, y: 304, z: 2});

    }

    // Create the bushes along the y-axis
    // We need to start one more and one less to not overlap the previous bushes
    for (var i = 1; i < 19; i++) {

      Crafty.e("2D, canvas, wall_left, bush" + Crafty.randRange(1,2))

        .attr({x: 0, y: i * 16, z: 2});

      Crafty.e("2D, canvas, wall_right, bush" + Crafty.randRange(1,2))

        .attr({x: 384, y: i * 16, z: 2});

    }
  }

  // The loading screen that will display while our assets load
  Crafty.scene("loading", function() {

    // Load takes an array of assets and a callback when complete
    Crafty.load(["sprite.png"], function() {

      Crafty.scene("main"); //when everything is loaded, run the main scene
    });

    // Black background with some loading text

    Crafty.background("#000");
    Crafty.e("2D, DOM, text").attr({w: 100, h: 20, x: 150, y: 120})

      .text("Loading")
      .css({"text-align": "center"});

  });

  // Automatically play the loading scene
  Crafty.scene("loading");
};

generateWorld() is a function that will create entities to fill up the stage. This is the first time we have created an entity so I will go over that first. The function to create an entity is simply Crafty.e(). That’s it. You can also pass a string of components to add which will just call the .addComponent() method. Have a look at the following lines of code:

grassType = Crafty.randRange(1, 4);

Crafty.e("2D, canvas, grass" + grassType)
  .attr({x: i * 16, y: j * 16});

When we spliced the sprite map, we had four types of grass components/labels: grass1, grass2, grass3 and grass4. Using a little helper method, Crafty.randRange(), we generate a random number between 1 and 4 to decide which grass tile to use and apply it to the entity.

You will notice we are also adding some odd-looking components: 2D and canvas. 2D is a very important component which gives the entity and x and y position, width and height (called .w and .h), rotation, alpha and some basic rectangle calculations. The other component, canvas, tells Crafty how to draw the entity and with this component obviously on the canvas element. You can just as easy use the DOM component and it will instead draw it as a <div>.

Tip: DOM is usually always faster than canvas and if you notice sluggish performance in a canvas entity, try using DOM. It will look and act no different.

The rest of the method generates a boundary around the stage so the player can’t walk off. This uses the bush sprite. These boundary entities have a component, either wall_left, wall_right, wall_up or wall_down. The only purpose they serve is as a label — there is no inherited functionality.

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web