- Home /
Animated Texture Offset
Hey,
First off, my game is a 2D side scroller. I am trying to create a 2D barrier, in which the texture's offset is changed over time. Currently, the texture is half transparent and half opaque. The opaque part of the texture is the barrier, and is viewable when the x-offset is 0.5. The transparent part is visible at 0.0. The script I have now animates the offset when the "TurnOn" or "TurnOff" functions are called. But, unfortunately, I am stumped as the offset is frequently a great deal away from the target value (causing some of the barrier to remain visible). Here is my code:
using UnityEngine;
using System.Collections;
public class Barrier : MonoBehaviour {
public bool on = true;
private float scrollSpeed;
private float offset;
private Vector2 currentOffset;
private float xOffset;
void Awake () {
if (on) {
TurnOn ();
} else {
TurnOff ();
}
}
void FixedUpdate () {
currentOffset = renderer.material.mainTextureOffset;
xOffset = currentOffset[0];
if (on && xOffset <= 0.5) {
offset = Time.time * scrollSpeed;
renderer.material.mainTextureOffset = new Vector2 (offset, 0);
}
if (!on && xOffset >= 0.0) {
offset += Time.time * -scrollSpeed;
renderer.material.mainTextureOffset = new Vector2 (offset, 0);
}
}
public void TurnOn () {
on = true;
offset = 0.0F;
scrollSpeed = 0.3F;
renderer.material.mainTextureOffset = new Vector2 (0.0F, 0.5F);
collider.enabled = true;
}
public void TurnOff () {
on = false;
offset = 0.5F;
scrollSpeed = 0.002F;
renderer.material.mainTextureOffset = new Vector2 (0.5F, 0.5F);
collider.enabled = false;
}
}
I feel as if there is a better way to solving this. Thank you in advance for any help!
-myjean17
Answer by numberkruncher · Mar 02, 2012 at 11:39 PM
I am not entirely sure what you are after but from what I can deduce here is how I would implement the above.
Warning, Not tested!
using UnityEngine;
using System.Collections;
public class Barrier : MonoBehaviour {
public bool on = true;
private float scrollSpeed;
private float offset;
private Material _material;
void Awake () {
_material = renderer.material;
if (on) {
TurnOn ();
} else {
TurnOff ();
}
}
void Update () {
float rate = scrollSpeed * Time.deltaTime;
if (on && offset <= 0.5f) {
offset = Mathf.Min(0.5f, offset + rate);
_material.mainTextureOffset = new Vector2 (offset, 0);
}
else if (!on && offset > 0.0f) {
offset = Mathf.Max(0.0f, offset - rate);
_material.mainTextureOffset = new Vector2 (offset, 0);
}
}
public void TurnOn () {
on = true;
offset = 0.0F;
scrollSpeed = 0.3F;
_material.mainTextureOffset = new Vector2 (0.0F, 0.5F);
collider.enabled = true;
}
public void TurnOff () {
on = false;
offset = 0.5F;
scrollSpeed = 0.002F;
_material.mainTextureOffset = new Vector2 (0.5F, 0.5F);
collider.enabled = false;
}
}
Thanks a ton kruncher. It works perfectly. I really appreciate your effort to help!