瓦片地图(Tilemap)

作者:追风剑情 发布于:2019-5-31 14:51 分类:Unity3d

一、准备精灵(sprite)素材

右键->Create->Sprites

22222.png

二、创建Tile

右键->Create->Tile

3333.png

三、创建Tile调色板(Tile Palette)

Window->Tile Palette

4444.png

Pixels Per Unit

222.png(每个Unity单位占100像素)

Tile Palette中的格子是一个Unity单位。100x100尺寸的Sprite刚好放满一个格子。

11111.png

技巧: 用鼠标选中一个Tile,按住鼠标左键不放,继续点击鼠标右键,会弹出右建菜单。

111.png

四、在场景中创建Tilemap

GameObject->2D Object->Tilemap

1111.png

五、编辑瓦片地图(Tilemap)

利用工具栏中的刷笔进行编辑地图

555.png

666.png

自定义Tile Asset

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.Tilemaps;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// TileBase: Tilemap中图块的基类
/// 自定义Tile
/// </summary>
public class CustomTile : TileBase
{
    public Sprite sprite;
    public Color color;
    public Tile.ColliderType colliderType;
    public GameObject gameObject;

    public Sprite[] animatedSprites;
    public float animationSpeed;
    public float animationStartTime;

    // 获取tile动画数据, 设置了动画数据后tile会播放精灵动画
    public override bool GetTileAnimationData(Vector3Int position, ITilemap tilemap, ref TileAnimationData tileAnimationData)
    {
        base.GetTileAnimationData(position, tilemap, ref tileAnimationData);
        tileAnimationData.animatedSprites = animatedSprites;
        tileAnimationData.animationSpeed = animationSpeed;
        tileAnimationData.animationStartTime = animationStartTime;
        return true;
    }

    // 获取tile数据,用来绘制tile
    public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
    {
        base.GetTileData(position, tilemap, ref tileData);
        tileData.sprite = sprite;
        tileData.color = color;
        tileData.flags = TileFlags.LockAll;
        tileData.colliderType = colliderType;
        tileData.gameObject = gameObject;//这个gameObject会被绘制到tile上
        tileData.transform = Matrix4x4.identity;//控制tile齐次变换
    }

    // tile刷新时调用
    public override void RefreshTile(Vector3Int position, ITilemap tilemap)
    {
        base.RefreshTile(position, tilemap);
    }

    // 游戏启动时调用一次
    public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject go)
    {
        return base.StartUp(position, tilemap, go);
    }

    #if UNITY_EDITOR
    [MenuItem("Assets/Create Custom Tile")]
    public static void CreateCustomTile()
    {
        CustomTile tile = ScriptableObject.CreateInstance<CustomTile>();
        AssetDatabase.CreateAsset(tile, "Assets/custom_tile.asset");
        AssetDatabase.Refresh();
    }
    #endif
}


111.png

运行效果

2222.gif

官方示例
Scriptable Tile example

自定义刷子(Brush)

11111.png

官方示例
Scriptable Brush example

刷地图时只能在当前激活的层刷

1111.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号