Summary of differences between 2.x project upgrade 3.x pit avoidance guide and basic API!

9d8eb230f9331f2f8efd29f7b9c7459a.jpeg

Some readers encountered many problems when upgrading Cocos Creator 2.x projects to 3.x, and felt very painful!

Fortunately, Xiaoheng had a similar experience last year. I upgraded my "Qiuqiu Wants to Go Home" on Cocos Store from Cocos Creator 2.2.2 to 2.4.10 and then to 3.6.2.

In this article, I will share with you some pitfalls I stepped on in the process and some changes in the most basic interfaces of the engine in 2.x and 3.x.

Whether you are upgrading an old project or want to try to start a new project on Creator 3.x, I believe this article can be helpful to you!

01 Upgrade process

1. Upgrade the engine to 2.4.x

If you are an old project below 2.4.x, it is recommended to upgrade the project to the latest engine version 2.4.x first.

If there is a warning or something, you can ignore it for the time being. The engine will prompt you which methods and attributes are obsolete, and what interface to use to replace them. You only need to change the truly abandoned interfaces to ensure the normal operation of the project.

According to my participation in CocosStore resource listing review and testing work in the past two years, 95% of the projects can be upgraded to 2.4.x without any changes.

2. Script upgrade

Cocos Creator 3.x only supports using TypeScript as component script.

Therefore, if you previously wrote component scripts in JavaScript, you will also need to translate them into TypeScript. This step is a physical activity:

  • One is to translate the script from JS to TS

  • The second is to remount the node with the script.

My approach is, for example, if I see a script: GameScene.js, first generate a script next to it GameSceneTS.ts. Follow the JS code logic and rewrite the code according to TS syntax.

058018244685cf23d35533999961e184.png

Although this is a laborious task, it is still very enjoyable to write TS code in VSCode, and the smart prompts are very convenient.

If you find code prompts, they are not as friendly as I said! Please note that you can update or import the prompt file through the engine 主菜单开发者, as shown in the figure:VSCode 工作流creator.d.ts

b5baee68ce3dfc7d3d9651e636ae3fa9.png

After the TS script is translated, it is time to replace it in the editor.

But, how to find the previously used JS script and where it was used? Look at the picture below:

912661559b3d43b2d3be06c4280610c3.png

In the resource manager, right-click the mouse to select the script file and click in the menu 找查使用to find the used resources 场景and 预制体.

But the problem comes again, there are so many nodes in the scene, where are the component scripts? How to find this?

3162156a09c7ad2e5d4d304fd0586127.png

Let me share a little trick here, enter in the search bar of the level manager: t:组件名字it will come out!96c229775afe834a69099d93d288f925.png

Then you can hang the new TS script on the node and configure the TS component parameters according to the previous JS component property values.

8f8943b684faade73db31b1a6c802826.png

After setting the TS component properties, remove the JS version of the component for testing. This operation can ensure that the project is consistent with the previous logic to the greatest extent and is less likely to cause problems.

After replacing all components, remove the JS script from the resource manager, and then remove the xxxTS suffix from the TS script name.

During the upgrade of "Qiuqiu Wants to Go Home" from 2.2.2 to 2.4.10, in addition to migrating the code scripts from JS to TS, I also rewritten all cc.Action actions into cc.Tween to prepare for the subsequent upgrade to 3. x Be well prepared.

3. Upgrade Creator 3.x project

Here comes the point, our goal is to successfully upgrade the 2.2.2 project to 3.6.2.

Create a new Creator 3.x project from the editor main menu 文件导入 Cocos Creator 2.x 项目

a0901f17f778cf5d3bf0fff7c4cc5191.png

Browse to the 2.x project directory to be upgraded, and a panel like the following will pop up.

0cda1cb2312bede2aa196fa64454b73e.png

Note: There is a pitfall here! I initially 球球要回家discovered after importing the 2.4.10 project that the Button button in the scene could not be clicked.

In order to eliminate the problem caused by the script, I rebuilt a Hello Worldproject using 2.4.10, added a Button button, and then imported 3.6.2. I still have this problem.

After trying many times with no solution, I stopped to read the instructions on the import panel and opened a Github repository, which is the plug-in version of this import tool.

997626c9b52e59ec0255be28539b35d2.png

Looking at the update instructions in the README, it just solves the problem of the button not being clickable, and fixes other bugs.

a24a6d6fe360d7b88bb199011a5e6586.png

Decisively download the plug-in and install it, try to use the Hello World project again to import the 3.x engine Button and click the problem to solve it!

4. Upgrade 3.x script code

Using the plug-in version import tool, after the import was completed, I felt my heart beating a little faster and carefully opened several game scenes and prefabs! shocked!

The UI is perfectly reproduced... OK
component script node is bound to... OK
component properties, node references, component method calls, everything is OK!
Is this a success?

I suppressed my excitement and tried to run it, and it started running!

But! Click the button, it just flicks, but nothing more.

I quickly opened the script and took a look, and found this situation: all the function bodies in the code were commented!

319e2913919ac3d1af915fa6c6a1c757.png

Only then did I realize that the real 3.x upgrade work has only begun now!

02 Component code adjustment

1. Module introduction

This form of API call cc.Nodeis deprecated in Creator 3.x. cc.SpriteInstead, make importthe module at the top of the script first, with the following code:

//从 cc 模块中解构出 Node、Sprite 变量
import { Node, Sprite } from 'cc'

In fact, when using VSCode to write code, we do not need to manually type in the imported importmodules one by one. See below:

b0be1e6f88b36dd81d16b6bc90b1916a.gif

When the engine module is used for the first time in the script, it will be automatically imported. If the above method does not work for you, you can try to install the VSCode prompt file through the 3.x engine main menu 开发者→ Install VSCode.Export.d.ts

c5a1cdccc59b21439e33c7cc7c3edec7.png

2. Changes in Node attributes

The properties of Node in Creator 3.x have become extremely concise, with only position, rotation, and scaleretained.

b05531dba786cffece6ff26f380ea9d6.png

What about the other attributes? We add a 2D sprite to the 3.x scene, and you can see:

94bf4469c450fb7728fc128a1425c8a4.png
  1. opacity attribute moved to cc.UIOpacitycomponent

  2. color attribute moved to cc.Spritecomponent

  3. The size and anchor point attributes are moved to cc.UITransformcomponents

90dbb49ad260d69072ed33a71ccc23f1.png

Therefore, the previous node.opacity, node.scale, node.color, node.width interfaces can no longer be used, and are replaced by the following interface methods:

Set node transparency

//Creator 2.x
this.node.opacity = 200;

//Creator 3.x
this.node.getComponent(UIOpacity).opacity = 200;

Set node color

//Creator 2.x 
this.node.color = cc.Color.RED;

//Creator 3.x
this.node.getComponent(Sprite).color = Color.RED;

Set node size

//Creator 2.x
this.node.setContentSize(100, 100);

//Creator 3.x 
let transform = this.node.getComponent(UITransform);
//使用方法设置节点大小
transform.setContentSize(100, 100)
//也可以使用contentSize属性
transform.contentSize = Size(100, 100);
//还可以使用width、height属性
transform.width = 100;
transform.height = 100;

Although the position, scale, and rotation attributes of Node in 3.x are still there, the code interface has also changed. Let's take a look at their differences.

Set node position

//Creator 2.x
this.node.position = v2(100, 100)
this.node.x = 100;  //3.x中不可用
this.node.y = 100;  //3.x中不可用

//Creator 3.x 中不能使用x、y、z分量设置节点位置
//需要使用 position 属性或 setPosition 方法
this.node.position = v3(100, 100, 100);
//注意需要同时设置 xyz 三个分量
this.node.setPosition(100, 100, 100);

Set node scaling

//Creator 2.x
this.node.scale = 1.5;

//Creator 3.x 
//注意 scale 不在是一个 number 而是 Vec3
this.node.scale = v3(1.5, 1.5, 1.5);
//注意 需要同时设置 xyz 三个分量
this.node.setScale(1,1,1);

Set the rotation of the node in two dimensions

//Creator 2.x rotation 属性在 2.3.x 之后是使用 angle 属性
this.node.angle = 1.5;

//Creator 3.x
//节点的 rotation 属性其实是一个 Quat 类型
//2D节点在属性检查器中的 rotation 
//对应的是节点的 angle 属性
this.node.angle = 10
//也可以使用 eulerAngles 来设置,注意它是设置的Z轴的旋转
this.node.eulerAngels = v3(0, 0, 10);

Node coordinate conversion

Also, commonly used node coordinate conversion interfaces in 2D such as convertToNodeSpaceAR, convertToWorldSpaceAR, and getBoundingBox have been moved to the UITransform component object. See the code:

//Creator 2.x 
let p = this.node.convertToNodeSpaceAR(eventTouch.location);

//Creator 3.x
let transform = this.node.getComponent(UITransform);
let location = eventTouch.location;
//注意 3.x 中convertToNodeSpaceAR的参数为 Vec3 类型
//但 location 为 Vec2 类型
let p = transform.convertToNodeSpaceAR(v3(location.x, location.y));

Tween animation

In Creator 2.x, Tween animation mainly controls the displacement, rotation, scaling, transparency, color and other attributes of nodes. Things to note after porting to Creator 3.x:

  1. Some properties are no longer in the Node object and need to be controlled by obtaining relevant components.

  2. The displacement, rotation, and scaling attributes use Vec3 type instead of Vec2, otherwise some unexpected problems will occur.

Like the scene below, when the level button appears, a zoom animation is made.b7648d16fc89201db8bda67260bad834.gif

The code is written like this:

...
let node = item.node;
tween(node)
  .to(0.1, { sacle: v2(1.1, 1.1) }) //放大
  .to(0.1, { sacle: v2(1, 1)})      //还原
  .start();

The operating results are also normal, but! The button cannot respond to the click event... After various troubleshooting, I found that it was caused by the Tween animation written, so I changed it to the following:

...
let node = item.node;
tween(node)
  .to(0.1, { sacle: v3(1.1, 1.1) }) //放大
  .to(0.1, { sacle: v3(1, 1)})      //还原
  .start();

After changing v2 to v3, it became normal immediately. It took me a long time to solve such a small problem.

Node level

In 2.x, Node.zIndexit is used to control the node display level. The larger the value, the lower level.

In 3.x, Node.zIndexthe interface has been abandoned and Node.setSiblingIndex() methods need to be used. This is the opposite of 2.x. The smallest value is at the bottom.

winSize

There is also a high-frequency interface in 2.x cc.winSizethat does not exist in 3.x. The corresponding API is to view.getContentSize()obtain the window design resolution size.

import { view } form 'cc'
view.getVisibleSize()

Editor loads resources

In projects, sometimes we use resource loading in the editor. What does it mean?

That is to say, I hope that I can see some interface effects in the editor state without running H5 preview. Moreover, the image resources used are not manually dragged and dropped in the editor, but loaded with code.

830dbf8c0ed87cdefebb6a096ddf6c02.gif

In the figure, you can directly see the scene changes by switching the level number through the properties GameBoardof the component . LevelStudents who don’t know how to do it may ask, how is this done?

  1. executeInEditModeAdd decorators to component scripts

import { _decorator } from 'cc';
const {ccclass, executeInEditMode} = _decorator;

@ccclass('GameBoard')
@executeInEditMode //添加编辑器模式执行
export default class GameBoard extends Component {
  onLoad() {
    //代码将在编辑器状态执行
  }
  start() {
    //代码将在编辑器状态执行
  }
  update() {
    //代码将在编辑器状态执行
  }
}

Note that executing code in the editor may cause some side effects, such as objects not being initialized and update being called frequently. 2.x At this time, you can use CC_EDITORvariables to check. The code is as follows:

//Creator 2.x 使用 CC_EDIDTO 全局变量检查
update() {
  if (CC_EDITOR) {
    return;
  }
  ...
}

There is no global in 3.x CC_EDITOR, but cc/envthe code under the module is as follows:

//Creator 3.x 使用 EDITOR 变量检查
import { EDITOR } from 'cc/env';
...
update() {
  if (EDITOR) {
    return;
  }
  ...
}

  1. Load resources in the editor

//Creator 2.4.x 加载图集中的图片
//注意'path'为resouces目录文件路径
cc.resources.load(path, SpriteAtlas, (err, res) => {
  let sprite = this.getComponent(Sprite);
  sprite.spriteFrame = res.getSpriteFrame(this.imageName);
});

Resources in the directory in 3.x Bundlecannot be loaded in the editor state, so the files need to be moved out of the resoucesdirectory and use assetManager.loadAnythis universal loading API. The code is as follows:

//Creator 3.x 加载图集中的图片
assetManager.loadAny({uuid:'xxx', type: SpriteAtlas}, (err, res) => {
  let sprite = this.getComponent(Sprite);
  sprite.spriteFrame = res.getSpriteFrame(this.imageName);
})

In my test, the interface form assetManager.loadAny({ {uuid:...}}) was used to load successfully. If you get the resource UUID, look at the picture below:

1c8aea591197f013a3c17ce8813f2192.jpeg

03 Summary

The overall process of porting from Creator 2.x to 3.x is roughly the following three steps:

  1. Migrate the code to TS and upgrade it to 2.4.x. If the project is already 2.4.x TS, congratulations, you can skip this step;

  2. Use the 2.x project import function in the 3.x editor (note that you must use a plug-in) to upgrade 2.x to 3.x. This step mainly solves the problem of UI redo;

  3. Modify the relevant interfaces in 3.x that are not compatible with 2.x. It is basically a one-to-one translation. Note that 3.x is a 3D engine first, and a large number of interfaces have been changed to Vec3.

I hope the above 2.x upgrade to 3.x content will be helpful to you "Qiuqiu Wants to Go Home"

Experience link:
http://gameview.creator-star.cn/zxh/ball-game-ccc3.6.2/index.html

Download address:
https://store.cocos.com/app/detail/2648


Past highlights

Guess you like

Origin blog.csdn.net/6346289/article/details/132179051