More Animating Problems

Alright, well, a while ago I had an issue where my main character was an animating texture (for a 2D game), so I posted the question asking why the script I found for animating a texture didn’t start at frame 1 every time it was called. I got some advice and just today I rewrote it to correct the problem. But now, the animation plays way too fast. :stuck_out_tongue:

var texture : Texture2D;
var animating = true;
var frameIndex = 1;
var lastframe = 4;


function Update () {
	if (animating == true) {
		InvokeRepeating ("Animate", 0, 2);
	}
}

function Animate () {
	frameIndex += 1;
	
	if(frameIndex > lastframe){
		frameIndex = 1;
	}
	
    texture.frame = frameIndex;
}

Thanks for all the help guys!

EDIT: Waaaait a second. It’s because I put the InvokeRepeating in an Update. So, here’s my new code:

var texture : Texture2D;
var animating = true;
var frameIndex = 1;
var lastframe = 4;
InvokeRepeating ("Animate", 0, 0.3);

function Animate () {
	frameIndex += 1;
	
	if(frameIndex > lastframe){
		frameIndex = 1;
	}
	
    texture.frame = frameIndex;
}

But it seems to be skipping the last frame…

The InvokeRepeating() function is probably getting called every frame since you’re not setting animating=false anywhere.

EDIT: Right, you saw that…

Aha, I’ve fixed it now!

var texture : Texture2D;
static var animating = true;
var frameIndex = 1;
var lastframe = 4;
InvokeRepeating ("Animate", 0.1, 0.2);

function Animate () {
	frameIndex += 1;
	
	if (frameIndex == lastframe){
		frameIndex = 0;
	}
	
    texture.frame = frameIndex;
}

Um… I guess I didn’t really have to post it… But it made me feel secure to know that if I couldn’t figure it out someone else would. :stuck_out_tongue:

If you want to tighten that up even more, you can use the modulus function thusly:

var texture : Texture2D; 
static var animating = true; 
var frameIndex = 1; 
var totalframes = 4; 
InvokeRepeating ("Animate", 0.1, 0.2); 

function Animate () {
    texture.frame = ++frameIndex % totalframes;
}

You’d be better off animating by combining frames into one texture and using the offset, however. Using movie frames has to upload the texture to the graphics card every frame so it’s a lot slower.

–Eric

Oy, that’s all a little over my head… this way works exactly as I need it to (and I’ll be sure to test on a slow computer as well).

It’s actually quite simple.

function Animate() {
	frameIndex += 1/totalframes;
	renderer.material.mainTextureOffset = Vector2(frameIndex,0);
}

Then just put the 4 frames side-by-side in one texture, and set the horizontal tiling of the texture to be 1/totalframes (.25 in this case). And make sure the texture is set to repeat instead of clamp, or change the second line to “renderer.material.mainTextureOffset = Vector2(frameIndex % totalframes,0);”.

–Eric