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.
Property Name | Property Type | Description |
---|---|---|
texture | Texture2D | Reference to the texture used |
width | Number | Width of the sprite. If the developer does not customize the sprite width, it defaults to the texture pixel width / 100 |
height | Number | Height of the sprite. If the developer does not customize the sprite height, it defaults to the texture pixel height / 100 |
region | Rect | Position of the sprite on the original texture, range 0 to 1 |
pivot | Vector2 | Position of the sprite's center point in the region on the original texture, range 0 to 1 |
border | Vector4 | When 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:
The pivot represents the position of the sprite's center in the region, as shown below:
In the Assets Panel, right-click on the blank area and select Upload → Sprite → Select 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
.
In the Assets Panel, right-click on the blank area and select Create → Sprite to create a blank sprite asset.
Similarly, in the script, we can create a sprite with the following code:
// 创建一个空白精灵
const sprite = new Sprite(engine);
// 创建一个带纹理的精灵
const spriteWithTexture = new Sprite(engine, texture2D);
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:
If the built-in values do not meet your needs, you can customize your own pivot, as shown below: