1
Introduction to integrates game thinking and game mechanics in a non-game environment to guide users to interact and use

Author of this article: Tao Department front-end team-Eva.js author-Ming Fei

2.35-1(无码).png

CodeDay#7 Beijing Railway Station registration, welcome to click register for free .

background

Now more and more companies and apps are beginning to use gamification to make products. The so-called gamification refers to the integration of game thinking and game mechanics in a non-game environment to guide users to interact and use method.

The Ant Manor and Ant Forest in Alipay realize the retention and activation of users through the combination of games and public welfare. Taobao Alipay’s Baba Farm, JD’s Dongdong Orchard, Pinduoduo’s Duoduo Orchard, Meituan’s Xiaomei Orchard... all are solutions to improve user retention through gamification.

In this article, we will list some gamified interactive games, and then split a case, take you to learn some of the most basic knowledge of 2D interaction, so that you can quickly write interactive games.

What can you do

1.png

Let’s look at a few 2D interactive projects. At present, most of the interactions are displayed in the form of games. Through game play and exquisite effects, users can have a better interactive experience. We develop, collect, and tower defense. , Catch the doll and other similar games, combined with business attributes, to achieve better business results.

Basic learning

Common 2D interaction capabilities

2.png

First, let's take a look at the common capabilities used in 2D interactive games. The first part is front-end knowledge, which mainly includes the drawing tools required for rendering, the game loop, and the ability to load resources.

Then there are basic drawing and animation capabilities, which are some of the basic elements of the game mentioned earlier. In game development, a lot of mathematics-related knowledge will be involved, such as letting the objects in the game simulate real physical effects, or the robots in the human-machine battles in some games, which are implemented using game AI. In this article Will not explain too much mathematics knowledge.

How the interactive game works

3.png

How does the interactive game work?

First of all, we know that many front-end projects currently drive views through data, and games are like this. For example, if we have an airplane in the game, then we need to define the size of the airplane and its position in the game. The airplane pictures corresponding to him are game data. We submit the data to the rendering engine, and the rendering engine renders the corresponding content to the canvas according to the content of the data.

The game runs dynamically. In order to achieve some animation/real physical effects, we use animation, AI, physics engine and other tools to control the changes of the data, and then continuously modify the data through loops, and render to the canvas to achieve the running of the game.

cycle

4.png

We know that the running effect of the game is achieved through loops. Next, let's take a look at how the game loop is implemented in the front-end browser environment.

The browser provides the requestAnimationFrame method, which requires the browser to call the specified callback function before the next drawing. This method is generally used to update the animation.

Every time the browser redraws is called 1 frame, the default drawing frequency of the browser is 60 frames, that is to say, under normal circumstances, the browser refreshes 60 times per second.

Through the following methods, we can ensure that before each frame is rendered, we can calculate the data and call the rendering method:

const loop = () => {
  requestAnimationFrame(loop)
  // 计算数据
  // 绘制图形
}
requestAnimationFrame(loop)

Because the requestAnimationFrame method will only be called before the next drawing, we need to call this method every time the method is called to ensure that the game continues to run, so this method will be called repeatedly in the loop method.

Under normal circumstances, we will put this method at the top of the function, because if an error is reported in the process of calculating data and drawing graphics, the program will not be able to execute this method, and the game will stop.

canvas

5.png

In html, we generally use the canvas tag to draw images. It does not have the ability to draw. Use getContext to get the drawing context and call the methods above the context to draw.

Commonly used drawing contexts are Canvas API and WebGL. Generally, CanvasAPI is used to draw 2D images. WebGL can draw 2D and 3D images, and its performance is higher.

Canvas provides some basic APIs, but the elements in interactive games are more complex, so there are generally rendering engines and game engines to undertake these elements.

This article will not explain Canvas in detail, you can learn from platforms such as MDN.

Basic rendering

Next, I will introduce, in 2D gamification interactive games, we often use several rendering schemes.

  • image
  • text
  • Graphics
  • Elves
  • Jiugongge
  • Mask

Needless to say, pictures and text are the most commonly used in view development. Let’s start with the graphics

Graphics

6.png

Generally, simple graphics are often used in development. Pictures are used not only to directly display content, but also to mask the rendered content. For example, a picture only displays the content in the graphic, and it is also used in the button area to judge. , The shape of the physics engine collision, and so on.

Elves

7.png

The sprite map is also the sprite map we touch in CSS, which is to combine multiple pictures into a large picture, and render a certain position in use. Through the sprite map, we can improve the network loading efficiency and rendering efficiency. Generally, sprite resources are composed of two files, one is a picture file, and the other is a location information file. Generally, when using the engine for rendering, you only need to care about the name of the corresponding thumbnail.

Jiugongge

We often encounter some pictures that are not fixed in size, but the surrounding or four-pass styles are not deformed, that is, .9 pictures, such as message bubbles. If you set the width and height directly, the entire bubble picture will be deformed.

8.png

Use the principle of Jiugongge to solve:

9.gif

The general rendering engine will also provide a convenient way to achieve.

Mask

10.gif

The masking effect of the rendered content can be achieved through the mask, is it very similar to setting overflow: hidden for the div?

Basic animation

Transition animation

For example, an object moves from 100px to 500px after 3 seconds. We can calculate by the following method.
startTime is the time when the animation starts.

11.png

If an object is moving at a constant speed to the right, we can use the formula s = v * t

12.png

Under normal circumstances, we will use a ready-made animation library, similar to Tween.js implementation, of course, when implementing complex animation logic, we can also use some tools, similar to Lottie, we still need handwritten animation.

Frame-by-frame animation

13.gif

14.png

Skeletal animation

Skeletal animation can simulate some more complex animations with certain joint logic. Compared with frame animation, it uses fewer pictures and takes up less memory.

Skeleton animation mainly consists of the following parts:

Skeleton animation map

15.png

Skeleton design and animation

16.gif

Texture+Bone+Animation

17.gif

Therefore, skeleton animation resources generally consist of three files. Commonly used skeleton animation design software is Spine and Dragonbones, which are generally designed by designers or animation designers. Developers only need to use the resources exported by the software.

Project actual combat

Knowing the above content, we can develop interactive projects. If you want to be good at your work, you must first sharpen your tools. Here we recommend Eva.js, which is open sourced by the Taoist Technology Department. It is a development dedicated to front-end developers. Designed by gamified interactive projects. At present, Taobao, Tmall, Alipay, Youku, Alibaba, AliExpress, Lazada, Koala and many other products are all in use. The Double 11 Cat Cat Project in 2020 is also implemented using Eva.js.

Next we take one of the simplest Demo to learn to use Eva.js.

18.gif

This is an animation of a heart moving left and right, and an alert pops up after clicking it.

19.png

The Eva.js game is composed of game objects and components. The game object represents an object in the game, and the component represents the object's capabilities. In this example, there is only one object, and its capabilities are three:

  • Picture shown as a heart
  • There is a left and right transition animation
  • Click event

We have just analyzed the capabilities required for this Demo, and then we have to do the four-step operation of Eva.js to develop the game

20.png

Step1 Add resources & create game
import { resource, Game } from '@eva/eva.js'
import { RendererSystem } from '@eva/plugin-renderer'
import { ImgSystem } from '@eva/plugin-renderer-img'
import { EventSystem } from '@eva/plugin-renderer-event'
import { TransitionSystem } from '@eva/plugin-transition'

resource.addResource([
  {
    name: 'imageName',
    type: RESOURCE_TYPE.IMAGE,
    src: {
      image: {
        type: 'png',
        url:
          '//gw.alicdn.com/bao/uploaded/TB1lVHuaET1gK0jSZFhXXaAtVXa-200-200.png',
      },
    },
    preload: true,
  },
]);

const game = new Game({
  systems: [
    new RendererSystem({
      canvas: document.querySelector('#canvas'),
      width: 750,
      height: 1000,
    }),
    new ImgSystem(),
    new EventSystem(),
    new TransitionSystem()
  ],
});

addResource is passed in a resource. There are not necessarily only image resources, but also frame animation, skeletal animation and other resources. Here we take image resources as an example. More demos can be viewed on the Eva.js official website.

After adding resources, we also created a game instance, which is the main runtime for running the game, because Eva.js has only one core game runtime, so all our functions need to be installed by ourselves~ so we To install the system, pictures, events, and animations needed for this game.

  • RendererSystem is a system used to render the game. All rendering capabilities rely on this system, which sets the width and height and the canvas object to be rendered.
  • ImgSystem is a system used to draw pictures
  • EventSystem is the system used to trigger click events
  • TransitionSystem is a system used to make displacement animation
Step2 Create objects and set positioning
import { GameObject } from '@eva/eva.js'

const heart = new GameObject('heart', {
  size: { width: 200, height: 200 },
  position: {
    x: 0,
    y: 0,
  },
  origin: { x: 0, y: 0 },
  anchor: {
    x: 0,
    y: 0,
  },
});

The first parameter of GameObject is the name of the object, and the second parameter is the position information of the object, where size sets the size of the object and position sets the position. You can refer to the documentation to learn about the others~

Step3 Add the required components

We just added the systems needed to realize the video function when we were in the new Game. These systems are used to read the values on the components and then realize the functions. Therefore, we need to add components to the object before the object can realize the corresponding function. .

The functions we currently need are image rendering, click events, and displacement animation, so we need to add three components

picture rendering

import { Img } from '@eva/plugin-renderer-img'

heart.addComponent(
  new Img({
    resource: 'imageName',
  }),
);

You can add components by calling the addComponent method of heart. Here we add the Img component. The Img component has a resource parameter, which is the name of the image resource, which actually corresponds to the name of the image resource added in Step1. Of course, Sprite and skeletal animation are also the same principle. You need to add resources to the resource and use them when adding components.

click event

import { Event } from '@eva/plugin-renderer-event'

const evt = heart.addComponent(new Event())
evt.on('tap', () => {
  alert(1)
})

Add an Event component to the game object, and bind the tap event through the on method. The second parameter of on is the function triggered by the tap event. Of course, the Event component has other events, which we can view through the Eva.js document.

Displacement animation

import { Transition } from '@eva/plugin-transition'

const transition = heart.addComponent(new Transition())
transition.group = {
  idle: [
    {
      name: 'position.x',
      component: heart.transform,
      values: [
        {
          time: 0,
          value: 0,
          tween: 'ease',
        },
        {
          time: 1000,
          value: 400,
          tween: 'ease',
        },
        {
          time: 2000,
          value: 0
        }
      ]
    }
  ]
}
transition.play('idle', Infinity)

In the above code, we have created an animation group called idle. In the current animation group, we change the value of the position.x property of the heart.transform component, 0->1000ms, the value is from 0->400, 1000ms-> 2000ms, the value is from 400->0, and then use the play method of the Transition component to make the animation execute Infinity times.

Step4 Run

Generally, games run automatically, so after finishing the above work, the game will automatically start running.

to sum up

There will be more and more gamified products in the future. The development of interactive games will become an essential skill for front-end engineers. Through this article, we can learn about some basic gamified interactive technologies and learn how to use Eva.js Realize one of the simplest interactive games.

If we want to go deeper into gamification and interactive technology, we need to learn game engines, rendering principles, animation, physics, sound effects and other technologies. For interactive business development, Eva.js can currently meet most of the needs.

The direction of gamification in the front-end field has just started. Eva.js is a game engine that focuses on developing gamification projects. It is also in its infancy. In the future, Eva.js will continue to focus on the front-end, focus on gamification projects, and make gamification projects. Development is simpler. We also hope that everyone can participate in the construction of the front-end gamification field, and we will continue to share relevant technologies and output gamification project development capabilities.


CodeDay#7 Beijing Station Registration

On July 17, we met in Zhongguancun with the mobile development industry technology leaders to explore the cutting-edge mobile terminal dynamic cross-terminal development plan.

KV.jpg

CodeDay#7 Beijing Railway Station registration, welcome to click register for free .

Copyright Notice: content of this article is contributed spontaneously by Alibaba Cloud real-name registered users. The copyright belongs to the original author. The Alibaba Cloud Developer Community does not own its copyright and does not assume corresponding legal responsibilities. For specific rules, please refer to the "Alibaba Cloud Developer Community User Service Agreement" and the "Alibaba Cloud Developer Community Intellectual Property Protection Guidelines". If you find suspected plagiarism in this community, fill in the infringement complaint form to report it. Once verified, the community will immediately delete the suspected infringing content.

阿里云开发者
3.2k 声望6.3k 粉丝

阿里巴巴官方技术号,关于阿里巴巴经济体的技术创新、实战经验、技术人的成长心得均呈现于此。