68 lines
2.1 KiB
C#
68 lines
2.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class SpriteAnim : MonoBehaviour
|
|
{
|
|
public int uvAnimationTileX = 10; //Here you can place the number of columns of your sheet.
|
|
public int uvAnimationTileY = 8; //Here you can place the number of rows of your sheet.
|
|
public float framesPerSecond = 10.0f;
|
|
public string ColorTexName = "_BaseMap";
|
|
public string EmissiveTexName = "_EmissiveMap";
|
|
public bool useEmissive = false;
|
|
private int colorTexID = -1;
|
|
private int emissiveTexID = -1;
|
|
Material mat;
|
|
// Start is called before the first frame update
|
|
void Start()
|
|
{
|
|
mat = GetComponent<Renderer>().material;
|
|
if (mat)
|
|
{
|
|
colorTexID = Shader.PropertyToID(ColorTexName);
|
|
emissiveTexID = Shader.PropertyToID(EmissiveTexName);
|
|
}
|
|
|
|
if (!mat.HasProperty(colorTexID))
|
|
{
|
|
Debug.LogError("Shader property not found: " + ColorTexName);
|
|
enabled = false;
|
|
}
|
|
|
|
if (useEmissive && !mat.HasProperty(emissiveTexID))
|
|
{
|
|
Debug.LogError("Shader property not found: " + EmissiveTexName);
|
|
enabled = false;
|
|
|
|
}
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
// Calculate index
|
|
int index = (int)(Time.time * framesPerSecond);
|
|
// repeat when exhausting all frames
|
|
index = index % (uvAnimationTileX * uvAnimationTileY);
|
|
|
|
// Size of every tile
|
|
var size = new Vector2(1.0f / uvAnimationTileX, 1.0f / uvAnimationTileY);
|
|
|
|
// split into horizontal and vertical index
|
|
var uIndex = index % uvAnimationTileX;
|
|
var vIndex = index / uvAnimationTileX;
|
|
|
|
// build offset
|
|
// v coordinate is the bottom of the image in opengl so we need to invert.
|
|
var offset = new Vector2(uIndex * size.x, 1.0f - size.y - vIndex * size.y);
|
|
|
|
mat.SetTextureOffset(colorTexID, offset);
|
|
mat.SetTextureScale(colorTexID, size);
|
|
|
|
if (useEmissive)
|
|
{
|
|
mat.SetTextureOffset(emissiveTexID, offset);
|
|
mat.SetTextureScale(emissiveTexID, size);
|
|
}
|
|
}
|
|
} |