Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use cocos creator to realize the game of synthetic watermelon

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use cocos creator to achieve the synthesis of big watermelon games", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use cocos creator to realize the game of synthesizing big watermelons.

Game logic

The logic of the whole game is relatively simple, combining Tetris and eliminating the core play of the game:

Is generating a fruit

Click on the screen, the fruit moves to the corresponding x-axis position and falls freely

Each fruit collides with other fruits, and when two identical fruits collide, they merge and upgrade to a higher level of fruit.

There are 11 types of fruit:

The goal of the game is to synthesize the most advanced fruit: big watermelon! The game ends when the accumulation of fruit exceeds the top red line.

Sort out the core logic that needs to be implemented:

Produce fruit

Fruit fall and collision

Fruit eliminates animation effect and upgrade logic

Preparatory work

Basic concepts of cocos creator

The whole project is implemented in cocos creator v2.4.3. It is recommended that students who know for the first time should go through the official documents first. This article will not introduce the use of creator too much (mainly because I am not very proficient).

Links to official documents:

Https://docs.cocos.com/creator/2.3/manual/zh/

Game material

First of all, we need to prepare art resources, all the art materials and audio materials come from:

Www.wesane.com/game/654/

First of all, visit the game website, open the network panel, you can see all the art resources that the game depends on, and we can download the files we need.

The required picture resources include:

11 fruit maps

Each kind of fruit synthesis effect map, including: a fruit grain picture, a round water drop picture, an explosion map

The synthesis of two watermelons has the effect of lighting and spreading flowers, but it will not be realized for the time limit.

Audio files are the same. You can quickly filter the corresponding resources by selecting the request with .mp3 suffix in the Filter column. The explosion sound and water sound when the fruit is eliminated, and the audio file is the same. You can select the request for .mp3 suffix in the Filter column to quickly screen the corresponding resources.

Create game scenes and backgrounds

Open cocos creator and create a new project (you can also import the project source code downloaded from github directly):

Https://github.com/tangxiangmin/cocos-big-watermelon

Then remember to drag the footage you just downloaded to the explorer in the lower right corner.

Create scene and background nodes

After the project is initialized, create a new game Scene in the lower left-hand corner of the explorer and name it game as the main scene of the game.

After you have created it, you can see the scene named game you just created in the assets of the explorer.

Select the game scene, and the Canvas canvas root node of the scene can be seen in the level manager in the upper left corner. The default cocos canvas is 960mm 640 on the horizontal screen. You can select the root node and adjust the width to 640mm 960 in the property inspector on the right.

Next, to create the background layer, we create a new background node under the Canvas node. Since the whole background is solid # FBE79D, we can fill it with a monochrome Sprite.

Also adjust the width and height of the background node to the size of the entire canvas, and since the default anchor point is 0.5cm 0.5, the entire canvas will be fully filled.

Now the whole game scene looks like this:

Next, design the logical script part of the game.

Scene script component

Create a new js script in the assets directory and conventionally command Game.js,creator to generate a template file with the underlying cc.Class.

First associate the script component with the node, select the Canvas root node, add the component in the property inspector on the right, and then select the Game component you just created.

Then write specific code logic and open the Game.js file (it is recommended that you use vscode or webstrom to open the root directory of the entire project for editing).

The initial code inside looks something like this:

/ / Game.jscc.Class ({extends: cc.Component, properties: {}, onLoad () {}, start () {}})

We need to maintain the logic of the entire game here, and then gradually add code content.

Create fruit

Fruit is the core element of the game, which is frequently created and destroyed in the game.

Generate a single fruit prefabricated resource

This dynamically created node can be controlled by a prefabricated resource Prefab, and the easiest way to make Prefab is to drag the asset from the explorer into the scene editor, and then drag the node in the hierarchy manager back to the explorer.

Here is an example of the lowest grade fruit "grape":

Then delete the nodes in the hierarchy manager so that we have a prefabricated resource for fruit, and in the script component, you can use code to dynamically generate nodes through prefabricated resources.

Modify Game.js to add an attribute fruitPrefab of type cc.Prefab:

/ / Game.js properties: {fruitPrefab: {default: null, type: cc.Prefab},}

Go back to creator, select the Canvas node, and you can see and modify the property in the Game components column in the property inspector.

We drag the prefab resource we just created from the explorer to here. During initialization, cocos is responsible for initializing the corresponding attribute data:

Create a single fruit

Go back to Game.js and start writing the real logic: create a grape.

/ / Game.js onLoad () {let fruit = cc.instantiate (this.fruitPrefab); fruit.setPosition (cc.v2 (0400)); this.node.addChild (fruit);}

In preview mode, you can see a grape directly above the screen:

Nice, that's a great start!

In addition, since the fruit contains some specific logic, we can add a Fruit scripting component to it, although it doesn't seem to be of much use yet!

Creating a Fruit script component is similar to creating a Game component above, and then select the prefab you just made to re-edit it, and associate it with the Fruit user script component.

Dynamic maintenance of multiple fruits

There are 11 kinds of fruits in the whole game (of course, you can add or change them to other things). If each kind of fruit is like above to manually generate prefabricated resources and initialize them separately, it will be too tedious. We need to solve the way to dynamically render multiple fruits.

We need to get the mapping information for each fruit, and then select the corresponding map when instantiating the fruit. The easiest way is to maintain a configuration table with id and iconSF data fields in each row.

Const FruitItem = cc.Class ({name: 'FruitItem', properties: {id: 0, / / Type of fruit iconSF: cc.SpriteFrame / / Map Resource}})

Then add a fruits attribute for the Game script component to hold the configuration information for each fruit, whose type is an array, and the element type in the array is the FruitItem you just created.

/ / Game.js properties: {fruits: {default: [], type: FruitItem},}

When you go back to the editor, you can find that there is an extra Fruits attribute under the attribute of the Game component, change its length to 11, then write the id of each fruit in turn, and paste its mapping resources from the resource editor (manual work).

In this way, we only need to pass in the id of the fruit we want to make, and we can get the corresponding configuration information and modify the map dynamically.

This initialization logic should be maintained by the fruit itself, so in the Fruit component we just created, we expose an init interface.

/ / Fruit.js properties: {id: 0,}, / / instance can be called in other components init (data) {this.id = data.id / / modify the mapping resource const sp = this.node.getComponent (cc.Sprite) sp.spriteFrame = data.iconSF} based on the passed parameters

Then modify the above code to initialize the fruit:

/ / Game.js createOneFruit (num) {let fruit = cc.instantiate (this.fruitPrefab); / / get the configuration information const config = this.fruits [num-1] / / get the Fruit component of the node and call the instance method fruit.getComponent ('Fruit'). Init ({id: config.id, iconSF: config.iconSF});}

In this way, you can happily create all kinds of fruits.

Monitor click events

Cocos provides a variety of event monitoring, front-end and client students will be no stranger.

The whole game creates a fruit when you click on the screen, just listen for the global click event, and this logic is also placed in the Game script component.

OnLoad () {/ / listen for click events this.node.on (cc.Node.EventType.TOUCH_START, this.onTouchStart, this)}, onTouchStart () {this.createOneFruit (1) / / generate fruit}

In the actual game, we also need to deal with the detailed logic such as randomly generated fruit and the fall of the last fruit on the x-axis clicked. I will not repeat it here.

Physical system: collision between free falling body and rigid body

The above deals with the logic of fruit creation. In the whole game, fruit can produce physical effects such as falling and elastic collision, which can be easily realized by using cocos's built-in physics engine.

Students who are not familiar with the cocos engine can take a look at this official demo, which is more detailed (at least easier to understand than the documentation).

Turn on physics engine and collision detection

The first is to turn on the physics engine and set the gravity size:

Const instance = cc.director.getPhysicsManager () instance.enabled = true / / instance.debugDrawFlags = 4 instance.gravity = cc.v2 (0,960)

Then you need to turn on collision detection, which is off by default:

Const collisionManager = cc.director.getCollisionManager (); collisionManager.enabled = true

Then set up the surrounding walls for collision so that the fruit does not fall down indefinitely:

/ / set the collision zone around let width = this.node.width; let height = this.node.height; let node = new cc.Node (); let body = node.addComponent (cc.RigidBody); body.type = cc.RigidBodyType.Static; const _ addBound = (node, x, y, width, height) = > {let collider = node.addComponent (cc.PhysicsBoxCollider); collider.offset.x = x; collider.offset.y = y; collider.size.width = width Collider.size.height = height;} _ addBound (node, 0,-height / 2, width, 1); _ addBound (node, 0, height / 2, width, 1); _ addBound (node,-width / 2,0,1, height); _ addBound (node, width / 2,0,1, height); node.parent = this.node

Now we have turned on the physics engine of the game world, and then we need to configure the nodes that need to be affected by the engine, that is, our fruit.

Fruit rigid body components and collision components

Go back to creator, find our fruit prefab, and add physical components.

The first is the Rigid Body (rigid body) component:

Then there are physical collision components, because our fruits are all round, so we can all choose PhysicsCircleCollider components. If there is an irregular polygon such as a banana, the workload will increase a lot.

Next, you can take a look at the overall effect (remember to add the click event just now, and then control the randomly generated fruit type):

Perfect!

Fruit collision callback

After the addition is complete, you also need to turn on the collision property Enabled Contact Listener of the rigid body component so that you can receive the callback after the collision.

This collision callback is also written in the Fruit script component:

/ Fruit.js onBeginContact (contact, self, other) {/ / detected a collision of two identical fruits if (self.node & & other.node) {const s = self.node.getComponent ('Fruit') const o = other.node.getComponent (' Fruit') if (s & o & & s.id = = o.id) {self.node.emit ('sameContact', {self, other}) }

In order to ensure the singleness of the function of the Fruit component, when two identical fruits collide, we notify Game.js through events, so that we can register the handling method of sameContact custom events when initializing the fruit.

/ / Game.js createOneFruit (num) {let fruit = cc.instantiate (this.fruitPrefab); / /. Other initialization logic fruit.on ('sameContact', ({self, other}) = > {/ / both node will be triggered temporarily to see if there is any other way to show the logic of other.node.off (' sameContact') / / handling fruit merging only once, and then deal with this.onSameFruitContact ({self, other})}}

In this way, when the fruit collides, we can monitor and eliminate the upgrade logic.

Eliminate fruit animation

No animated version

The simple elimination logic is to delete the two nodes and then generate a higher-level fruit in the original fruit position without any animation:

Self.node.removeFromParent (false) other.node.removeFromParent (false) const {x, y} = other.node / / get the merged fruit location const id = other.getComponent ('Fruit'). Id const nextId = id + 1 const newFruit = this.createFruitOnPos (x, y, nextId) / / generate new fruit at the specified location

Although it looks a little strange, but it can be played!

Analyze animation

Open the origin server and analyze the animation effects through the Performance panel (gif will not be recorded here).

You can see that the animation effects when compositing include:

The collision fruit moves to the center of the original fruit

The particle effect of fruit explosion

Particle effect of water droplet explosion

Zoom animation of a pool of juice

In addition, there are the sound effects of explosions and water.

Manage explosive material resources

As the whole animation involves a large number of materials, each fruit contains three different color maps, similar to the above FruitItem, we also use prefab plus dynamic resources to manage the corresponding material and animation logic.

First, define a JuiceItem to save the material needed for a single fruit explosion:

/ / Game.js const JuiceItem = cc.Class ({name: 'JuiceItem', properties: {particle: cc.SpriteFrame, / / fruit circle: cc.SpriteFrame, / / water drop slash: cc.SpriteFrame, / / fruit juice}})

Then add a juices property to the Game component:

/ / Game.js properties: {juices: {default: [], type: JuiceItem}, juicePrefab: {default: null, type: cc.Prefab},}

Next, it's time to sell labor. Drag and drop all the map resources under the juices attribute:

Then add an empty prefabricated resource, mainly to mount the script component, that is, the following Juice script, and then remember to mount the prefabricated resource to Game's juicePrefab.

Finally, create a new Juice component to implement the explosion animation logic, and you also need to expose the init interface:

/ Juice.js cc.Class ({extends: cc.Component, properties: {particle: {default: null, type: cc.SpriteFrame}, circle: {default: null, type: cc.SpriteFrame}, slash: {default: null Type: cc.SpriteFrame}}, / / also expose an init interface init (data) {this.particle = data.particle this.circle = data.particle this.slash = data.slash}, / / Animation showJuice () {}}

So, when merging, we initialize a Juice node and show the explosion effect at the same time.

/ / Game.js let juice = cc.instantiate (this.juicePrefab); this.node.addChild (juice); const config = this.juices [id-1] const instance = juice.getComponent ('Juice') instance.init (config) instance.showJuice (pos, n) / / corresponding explosion logic

Explosive particle animation

With regard to particle animation, a lot of information can be found on the Internet. If you are interested, you can also follow the common principles of front-end animation that I sorted out before:

Https://www.shymean.com/article/%E5%89%8D%E7%AB%AF%E5%B8%B8%E8%A7%81%E5%8A%A8%E7%94%BB%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86

The main idea of particle animation is to initialize N particles, control their speed, direction and life cycle, and then control each particle to execute animation according to the corresponding parameters. the effect of all the particles together constitutes the particle animation.

Having said that, it is troublesome to adjust the animation effect, and you need to control a variety of random parameters.

ShowJuice (pos, width) {/ / Fruit for (let I = 0; I < 10; + + I) {const node = new cc.Node ('Sprite'); const sp = node.addComponent (cc.Sprite); sp.spriteFrame = this.particle; node.parent = this.node; / / A bunch of random parameters node.position = pos; node.runAction (cc.sequence (/ /... Animation logic cc.callFunc (function () {/ / eliminate particles node.active = false}, this) corresponding to various action)} / / droplet for (let f = 0; f < 20) Fido +) {/ / same fruit, switch spriteFrame to this.circle} / / juice with only one map, use this.slash to show regular action scaling and transparent animation}

The source project code uses createFruitL this method to deal with explosion animation, although after the code compression, but can vaguely see the corresponding animation parameter logic, if you do not want to adjust the animation parameters, you can learn from it.

In this way, the display of the explosion effect is completed, which is probably similar to this, though a little ugly.

Sound effect

Directly play AudioClip resources through cc.audioEngine to achieve sound effects.

Add two new resources of type AudioClip under the Game component to facilitate access by the script component:

Properties: {boomAudio: {default: null, type: cc.AudioClip}, waterAudio: {default: null, type: cc.AudioClip}}

As above, drag two audio resources from the explorer to the properties of the Game component in the property inspector:

OnSameFruitContact () {cc.audioEngine.play (this.boomAudio, false, 1); cc.audioEngine.play (this.waterAudio, false, 1);}

So you can hear the sound in the event of a collision.

Build Packaging

After you have completed the development of the entire game, you can choose to build and release it, package it into a web-mobile version, and then deploy it on the server so that others can have fun.

At this point, I believe you have a deeper understanding of "how to use cocos creator to achieve the synthesis of big watermelon games". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report