-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScratchySprite.cs
More file actions
533 lines (478 loc) · 16.3 KB
/
ScratchySprite.cs
File metadata and controls
533 lines (478 loc) · 16.3 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class ScratchySprite : ScratchyObject
{
public Sprite[] Costumes;
// public ScratchyCostume[] Costumes;
protected SpriteRenderer spriteRenderer;
private int costumeNumber = -1;
private int CollisionAccuracy = 1;
internal static Dictionary<Type, List<ScratchySprite>> Instances = new Dictionary<Type, List<ScratchySprite>>();
/// <summary>
/// Initialization
/// </summary>
public override void Start()
{
base.Start();
spriteRenderer = GetComponent<SpriteRenderer>();
NextCostume();
}
public float Rotate(float degrees)
{
this.transform.Rotate(0, 0, degrees);
return this.transform.rotation.z;
}
private void RegisterInstance()
{
Type t = this.GetType();
if (!Instances.ContainsKey(t))
{
Instances[t] = new List<ScratchySprite>();
}
if (!Instances[t].Contains(this))
{
Instances[t].Add(this);
}
}
private void UnregisterInstance()
{
Type t = this.GetType();
if (Instances[t].Contains(this))
{
Instances[t].Remove(this);
}
}
public void OnEnable()
{
RegisterInstance();
}
public void OnDisable()
{
UnregisterInstance();
}
public void OnDestroy()
{
UnregisterInstance();
}
/// <summary>
/// Switch to the next costume
/// </summary>
public void NextCostume()
{
if (Costumes.Length == 0)
{
return;
}
costumeNumber++;
if (costumeNumber >= Costumes.Length)
{
costumeNumber = 0;
}
SetCostume(costumeNumber);
}
/// <summary>
/// Gets or sets the costume number
/// </summary>
public int CostumeNumber
{
get
{
return costumeNumber;
}
set
{
SetCostume(value);
}
}
/// <summary>
/// Set the costume numberr
/// </summary>
/// <param name="costumeNumber">The costume number (0 based)</param>
public void SetCostume(int costumeNumber)
{
this.costumeNumber = costumeNumber % this.Costumes.Length;
var costume = Costumes[CostumeNumber];
if (costume != null && spriteRenderer != null)
{
spriteRenderer.sprite = costume;
}
}
/// <summary>
/// Set the active costume by name
/// </summary>
/// <param name="costumeName">Name of the costume to use (case sensitive)</param>
public void SetCostume(string costumeName)
{
int costumeCount = this.Costumes.Length;
for (int i = 0; i < this.Costumes.Length; i++)
{
if (this.Costumes[i].name == costumeName)
{
this.SetCostume(i);
return;
}
}
Debug.LogWarning(this.name + " costume '" + costumeName +"' not found.");
}
/// <summary>
/// Show this ScratchySprite if it has been hidden
/// </summary>
public void Show()
{
this.spriteRenderer.enabled = true;
}
/// <summary>
/// Hide this ScratchySprite
/// </summary>
public void Hide()
{
this.spriteRenderer.enabled = false;
}
/// <summary>
/// X position in world space
/// </summary>
public double X
{
get
{
return this.transform.position.x;
}
set
{
this.transform.position = new Vector3((float)value, transform.position.y, transform.position.z);
}
}
/// <summary>
/// Y position in world space
/// </summary>
public double Y
{
get
{
return this.transform.position.y;
}
set
{
this.transform.position = new Vector3(transform.position.x, (float)value, transform.position.z);
}
}
/// <summary>
/// Z position in world space
/// </summary>
public double Z
{
get
{
return this.transform.position.z;
}
set
{
this.transform.position = new Vector3(transform.position.x, transform.position.y, (float)value);
}
}
/// <summary>
/// Z rotation
/// </summary>
public float Rotation
{
get
{
// todo: not right
return this.transform.rotation.eulerAngles.z;
}
set
{
this.transform.rotation = Quaternion.Euler(0, 0, value);
}
}
/// <summary>
/// Z direction
/// </summary>
public float Direction
{
get
{
return direction.HasValue ? direction.Value : this.Rotation;
}
set
{
direction = value;
}
}
private float? direction;
/// <summary>
/// Destroy this ScratchySprite instance
/// </summary>
public void Destroy()
{
UnityEngine.Object.Destroy(this.gameObject);
}
/// <summary>
/// Gets the sprite renderer for this ScratchySprite
/// </summary>
public SpriteRenderer SpriteRenderer
{
get
{
if (_spriteRenderer == null)
{
_spriteRenderer = GetComponent<SpriteRenderer>();
}
return _spriteRenderer;
}
}
private SpriteRenderer _spriteRenderer;
/// <summary>
/// Get the bounds of this sprite in world space
/// </summary>
/// <returns>Bounds of this sprite in world space</returns>
public Bounds GetWorldBounds()
{
return this.SpriteRenderer.bounds;
/* The long way -->
Bounds bounds = this.SpriteRenderer.sprite.bounds;
Vector3 c1 = this.transform.TransformPoint(bounds.min);
Vector3 c2 = this.transform.TransformPoint(bounds.max);
Vector3 c3 = this.transform.TransformPoint(new Vector3(bounds.max.x, bounds.min.y, bounds.min.z));
Vector3 c4 = this.transform.TransformPoint(new Vector3(bounds.min.x, bounds.max.y, bounds.min.z));
// Debug.DrawLine(c1, c2, Color.gray);
Bounds transformedBounds = new Bounds();
transformedBounds.SetMinMax(
new Vector3(
Mathf.Min(c1.x, Mathf.Min(c2.x, Mathf.Min(c3.x, c4.x))),
Mathf.Min(c1.y, Mathf.Min(c2.y, Mathf.Min(c3.y, c4.y))), 0),
new Vector3(
Mathf.Max(c1.x, Mathf.Max(c2.x, Mathf.Max(c3.x, c4.x))),
Mathf.Max(c1.y, Mathf.Max(c2.y, Mathf.Max(c3.y, c4.y))), 0));
Debug.Log("TB: " + transformedBounds + " RB:" + this.SpriteRenderer.bounds);
return transformedBounds;
*/
}
/// <summary>
/// Get the bounds of this sprite in world space
/// </summary>
/// <param name="c"></param>
public void DrawWorldBounds(Color c)
{
Bounds bt = GetWorldBounds();
DrawRectangle(bt, c);
}
/// <summary>
/// Find a ScratchySprite with the given name
/// </summary>
/// <param name="spriteName"></param>
/// <returns></returns>
public ScratchySprite FindSprite(string spriteName)
{
var go = GameObject.Find(spriteName);
if (go != null)
{
return go.GetComponent<ScratchySprite>();
}
return null;
}
/// <summary>
/// Get the color of the pixel for this sprite at the given coordinates in sprite local space
/// </summary>
/// <param name="objectX">X position in sprite local space</param>
/// <param name="objectY">Y position in sprite local space</param>
/// <returns>Color of the pixel</returns>
private Color32 GetPixel(float objectX, float objectY)
{
Rect tr = this.SpriteRenderer.sprite.textureRect;
var pivotPointOffset = new Vector3(tr.center.x - tr.xMin, tr.center.y - tr.yMin, 0);
return this.SpriteRenderer.sprite.texture.GetPixel((int)(tr.x + pivotPointOffset.x + objectX), (int)(tr.y + pivotPointOffset.y + objectY));
}
/// <summary>
/// Get all of the sprites of a given type that are touching this sprite
/// </summary>
/// <typeparam name="T">Type of sprite to check</typeparam>
/// <returns>List of touching sprites</returns>
public List<T> GetTouchingSprites<T>() where T : ScratchySprite
{
List<T> touching = new List<T>();
foreach (var sprite in GetSprites<T>())
{
if (IsTouching(sprite))
{
touching.Add((T)sprite);
}
}
return touching;
}
/// <summary>
/// Get a single touching sprite of a given type
/// </summary>
/// <typeparam name="T">Type of sprite to check</typeparam>
/// <returns>The touching sprite object, or null if none are touching</returns>
public T GetTouchingSprite<T>() where T : ScratchySprite
{
foreach (var sprite in GetSprites<T>())
{
if (IsTouching(sprite))
{
return (T)sprite;
}
}
return null;
}
/// <summary>
/// Are any sprites of the given type touching this sprite
/// </summary>
/// <typeparam name="T">The type of sprite to check</typeparam>
/// <returns>True if any are touching, otherwise False</returns>
public bool IsTouchingAny<T>() where T : ScratchySprite
{
foreach (var sprite in GetSprites<T>())
{
if (IsTouching(sprite))
{
return true;
}
}
return false;
}
/// <summary>
/// Is this sprite touching the other sprite (pixel perfect collission)
/// </summary>
/// <param name="other">The other sprite object to check</param>
/// <returns>True if they are touching</returns>
public bool IsTouching(ScratchySprite other)
{
if (other == null)
{
return false;
}
Bounds thisWorldBounds = this.GetWorldBounds();
Bounds otherWorldBounds = other.GetWorldBounds();
bool collision = thisWorldBounds.Intersects(otherWorldBounds);
// World bounding rects intersect, now check pixels
if (collision)
{
collision = false;
Bounds worldIntersection = thisWorldBounds.Intersect(otherWorldBounds);
Bounds thisSpriteBounds = this.SpriteRenderer.sprite.bounds;
Bounds otherSpriteBounds = other.SpriteRenderer.sprite.bounds;
Vector3 pixelWorldPos;
Color32 c;
for (float x = thisSpriteBounds.min.x + 0.5f; x < thisSpriteBounds.max.x && !collision; x += CollisionAccuracy)
{
for (float y = thisSpriteBounds.min.y + 0.5f; y < thisSpriteBounds.max.y && !collision; y += CollisionAccuracy)
{
pixelWorldPos = this.transform.TransformPoint(new Vector3(x, y, 0));
if (worldIntersection.Contains(pixelWorldPos))
{
c = GetPixel(x, y);
if (c.a > 0)
{
// Get this pixel position in other sprite
Vector3 otherLocalPos = other.transform.InverseTransformPoint(pixelWorldPos);
if (otherSpriteBounds.Contains(otherLocalPos))
{
if (other.GetPixel(otherLocalPos.x, otherLocalPos.y).a > 0)
{
collision = true;
}
}
}
}
}
}
}
return collision;
}
/// <summary>
/// Is the sprite touching or outside of the camera's view
/// </summary>
/// <returns>True if any corner of the sprite is outside of the camera's view</returns>
public bool IsTouchingEdge()
{
Bounds cameraBounds = Camera.main.OrthographicBounds();
Bounds spriteBounds = this.GetWorldBounds();
return !cameraBounds.Contains(spriteBounds.min) || !cameraBounds.Contains(spriteBounds.max)
|| !cameraBounds.Contains(new Vector3(spriteBounds.min.x, spriteBounds.max.y, 0))
|| !cameraBounds.Contains(new Vector3(spriteBounds.max.x, spriteBounds.min.y, 0));
}
/// <summary>
/// Move some distance in either the current direction or a given direction
/// </summary>
/// <param name="distance">Distance to move</param>
/// <param name="direction">Direction to move, or null to use the sprites direction or rotation</param>
public void Move(float distance, float? direction = null)
{
float dir;
if (direction.HasValue)
{
dir = direction.Value;
}
else
{
dir = this.Direction;
}
var d = Quaternion.Euler(0, 0, dir) * Vector3.up;
this.transform.Translate(d * distance, Space.World);
}
/// <summary>
/// Convert the sprite's current costume to a collection of quads
/// </summary>
public List<GameObject> ConvertToPixelQuads(bool addBoxCollider, bool addPhysics, float explosionForce)
{
Color32 c;
List<GameObject> pixels = new List<GameObject>();
Bounds thisSpriteBounds = this.SpriteRenderer.sprite.bounds;
List<Type> components = new List<Type> { typeof(MeshRenderer), typeof(MeshFilter) };
if (addBoxCollider)
{
components.Add(typeof(BoxCollider2D));
}
if (addPhysics)
{
components.Add(typeof(Rigidbody2D));
}
var componentArray = components.ToArray();
for (float x = thisSpriteBounds.min.x + 0.5f; x < thisSpriteBounds.max.x; x += CollisionAccuracy)
{
for (float y = thisSpriteBounds.min.y + 0.5f; y < thisSpriteBounds.max.y; y += CollisionAccuracy)
{
// Is the pixel transparent, or does it have a color
c = GetPixel(x, y);
if (c.a > 0.5f)
{
// Create a pixel object
float size = -.5f;
Mesh m = new Mesh();
m.name = "PixelMesh";
m.vertices = new[] { new Vector3(-size, -size, 0.01f), new Vector3(size, -size, 0.01f), new Vector3(size, size, 0.01f), new Vector3(-size, size, 0.01f) };
m.uv = new[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) };
m.triangles = new[] { 0, 1, 2, 0, 2, 3 };
m.RecalculateNormals();
GameObject p = new GameObject("Pixel", componentArray);
p.GetComponent<MeshFilter>().mesh = m;
// Configure physics
if (addPhysics) {
p.GetComponent<Rigidbody2D>().gravityScale = 10f;
}
if (addBoxCollider) {
p.GetComponent<BoxCollider2D>().size = Vector2.one;
}
// Color the pixel
p.renderer.material.color = c;
p.renderer.material.shader = this.renderer.material.shader;
// Position it
p.transform.position = new Vector3(x, y, (float)this.Z);
p.transform.SetParent(this.transform, false);
p.transform.SetParent(null, true);
// Add it to the list
pixels.Add(p);
// Explode
if (explosionForce > 0) {
p.GetComponent<Rigidbody2D>().AddForceAtPosition(new Vector2(x, y) * explosionForce * UnityEngine.Random.Range(.5f, 2f), Vector2.zero);
}
}
}
}
return pixels;
}
}