2D

Sprite

Sprite is the most important asset in 2D projects. It obtains graphical source data from Texture2D and customizes the desired rendering result by setting properties such as region and pivot. If assigned to a SpriteRenderer, the node with the sprite renderer can display 2D images in three-dimensional space. If assigned to a SpriteMask, the node with the sprite mask can achieve masking effects for corresponding 2D elements. Next, let's delve into the properties and usage of sprites.

Properties

Property NameProperty TypeDescription
textureTexture2DReference to the texture used
widthNumberWidth of the sprite. If the developer does not customize the sprite width, it defaults to the texture pixel width / 100
heightNumberHeight of the sprite. If the developer does not customize the sprite height, it defaults to the texture pixel height / 100
regionRectPosition of the sprite on the original texture, range 0 to 1
pivotVector2Position of the sprite's center point in the region on the original texture, range 0 to 1
borderVector4When the renderer's drawing mode is nine-slice or tiled, the border configuration affects the final rendering effect. x, y, z, w correspond to the distances from the left, bottom, right, and top edges, respectively

The region determines the display content of the sprite. You can select a rectangular area in the texture to display, and the excess part will be automatically filtered out, as shown below:

avatar

The pivot represents the position of the sprite's center in the region, as shown below:

avatar

Usage

Creation

Upload Sprite

In the Assets Panel, right-click on the blank area and select UploadSpriteSelect the corresponding image to upload the sprite asset. After a successful upload, the current asset list will synchronously add a texture asset named image_name.png and a sprite asset named image_name-spr.png.

avatar

Create Blank Sprite

In the Assets Panel, right-click on the blank area and select CreateSprite to create a blank sprite asset.

avatar

Script Creation

Similarly, in the script, we can create a sprite with the following code:

// 创建一个空白精灵
const sprite = new Sprite(engine);
// 创建一个带纹理的精灵
const spriteWithTexture = new Sprite(engine, texture2D);

Set Properties

Here, we specifically explain the setting of the pivot in the editor. For the pivot, the bottom-left corner of the texture is (0, 0), the X-axis goes from left to right, and the Y-axis goes from bottom to top. The editor has some built-in common pivot shortcut values, as shown below:

avatar

If the built-in values do not meet your needs, you can customize your own pivot, as shown below:

avatar

Was this page helpful?