-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubtexture.cs
96 lines (73 loc) · 2.66 KB
/
Subtexture.cs
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
90
91
92
93
94
95
96
using UnityEngine;
using System.Collections.Generic;
namespace Binocle
{
/// <summary>
/// represents a single element in a texture atlas consisting of a texture and the source rectangle for the frame
/// </summary>
public class Subtexture
{
/// <summary>
/// the actual Texture2D
/// </summary>
public Texture2D texture2D;
/// <summary>
/// rectangle in the Texture2D for this element
/// </summary>
public Rect sourceRect;
/// <summary>
/// center of the sourceRect if it had a 0,0 origin. This is basically the center in sourceRect-space.
/// </summary>
/// <value>The center.</value>
public Vector2 center;
public Subtexture(Texture2D texture, Rect sourceRect)
{
this.texture2D = texture;
this.sourceRect = sourceRect;
center = sourceRect.size * 0.5f;
}
public Subtexture(Texture2D texture) : this(texture, new Rect(0, 0, texture.width, texture.height))
{
}
public Subtexture(Texture2D texture, int x, int y, int width, int height) : this(texture, new Rect(x, y, width, height))
{
}
/// <summary>
/// convenience constructor that casts floats to ints for the sourceRect
/// </summary>
/// <param name="texture">Texture.</param>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <param name="width">Width.</param>
/// <param name="height">Height.</param>
public Subtexture(Texture2D texture, float x, float y, float width, float height) : this(texture, (int)x, (int)y, (int)width, (int)height)
{
}
public static List<Subtexture> subtexturesFromAtlas(Texture2D texture, int cellWidth, int cellHeight)
{
var subtextures = new List<Subtexture>();
var cols = texture.width / cellWidth;
var rows = texture.height / cellHeight;
for (var y = 0; y < rows; y++)
{
for (var x = 0; x < cols; x++)
{
subtextures.Add(new Subtexture(texture, new Rect(x * cellWidth, y * cellHeight, cellWidth, cellHeight)));
}
}
return subtextures;
}
public virtual void unload()
{
texture2D = null;
}
public static implicit operator Texture2D(Subtexture tex)
{
return tex.texture2D;
}
public override string ToString()
{
return string.Format("{0}", sourceRect);
}
}
}