-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTilemapRender.cs
More file actions
89 lines (66 loc) · 2.9 KB
/
TilemapRender.cs
File metadata and controls
89 lines (66 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using Stride.Core.Mathematics;
using Stride.Engine;
using Stride.Graphics;
using Stride.Rendering;
using Stride.Rendering.Compositing;
using TiledSharp;
namespace TilemapStride
{
public class TilemapRender : SceneRendererBase
{
private SpriteBatch? spriteBatch;
public static TmxMap? map;
private Texture? tileset;
private Scene? scene;
private CameraComponent? camera;
public static int tileWidth;
public static int tileHeight;
int tilesetTilesWidth;
int tilesetTilesHeight;
protected override void InitializeCore()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
map = new TmxMap("res/tilemap.tmx");
if (map == null) Console.WriteLine("map not loaded");
else Console.WriteLine("map loaded");
using var input = File.Open("res/texture.png", FileMode.Open);
tileset = Texture.Load(GraphicsDevice, input);
tileWidth = map.Tilesets[0].TileWidth;
tileHeight = map.Tilesets[0].TileHeight;
tilesetTilesWidth = tileset.Width / tileWidth;
tilesetTilesHeight = tileset.Height / tileHeight;
}
protected override void DrawCore(RenderContext context, RenderDrawContext drawContext)
{
if (map == null || tileset == null || spriteBatch == null) return;
var graphicsCompositor = context.Tags.Get(GraphicsCompositor.Current);
if (graphicsCompositor == null) return;
camera ??= graphicsCompositor.Cameras[0].Camera;
scene ??= SceneInstance.GetCurrent(context).RootScene;
var camPos = camera?.Entity?.Transform?.Position ?? new Stride.Core.Mathematics.Vector3();
float camOffsetX = camPos.X;
float camOffsetY = camPos.Y;
for(int i = 0; i < map.Layers.Count; i++)
{
spriteBatch.Begin(drawContext.GraphicsContext);
for (var ty = 0; ty < map.Height; ty++)
{
for (var tx = 0; tx < map.Width; tx++)
{
var tile = map.Layers[i].Tiles[tx + ty * map.Width];
int gid = tile.Gid;
if (gid == 0) continue;
int tileFrame = gid - 1;
int column = tileFrame % tilesetTilesWidth;
int row = tileFrame / tilesetTilesWidth;
int x = tx * map.TileWidth;
int y = ty * map.TileHeight;
Rectangle tilesetRec = new Rectangle(tileWidth * column, tileHeight * row, tileWidth, tileHeight);
spriteBatch.Draw(tileset, new Vector2(x - camOffsetX, y - camOffsetY), tilesetRec, Color4.White);
}
}
spriteBatch.End();
}
}
}
}