Hello, dear community! I would like to create a casting bar UI, and have found a wonderful tutorial here: Unity Tutorial: Unity 4.6 - Using the new UI to create a casting bar - YouTube. However, I decided to write a script myself. It works almost as intended: the bar moves from start position to the end position smoothly no matter what time interval I set (1 second or 10 seconds doesn’t matter). But it moves slightly more than it should.
Because of this - because the bar arrives always at exact time to the wrong position - it seems the problem lies in the way “rate” variable is calculated. Please have a look, for your convenience I am attaching C# script and screenshots. Your comments are welcome!
using UnityEngine;
using System.Collections;
public class castingbarscript : MonoBehaviour {
public GameObject castbar;
public Vector3 startpos;
public Vector3 endpos;
public Vector3 Resultpos;
public float timer1;
public bool doing;
public float rate;
// Use this for initialization
void Start () {
startpos = castbar.transform.position;
// startpos = new Vector3 (0,0,0);
endpos = new Vector3(castbar.transform.position.x - castbar.GetComponent<RectTransform>().rect.width, castbar.transform.position.y,castbar.transform.position.z);
// endpos = new Vector3 (155, 0, 0);
Resultpos = startpos - endpos;
doing = false;
timer1 = 1f;
rate = (Resultpos.x/timer1)*Time.deltaTime;
}
// Update is called once per frame
void Update () {
Debug.Log (castbar.transform.position);
if (Input.GetKeyDown (KeyCode.J)) {
doing = true;
}
//reset
if (Input.GetKeyDown (KeyCode.L)) {
doing = true;
castbar.transform.localPosition = new Vector3 (0,0,0);
timer1 = 1f;
}
if (doing) {
timer1 -= Time.deltaTime;
if(timer1 >= 0){
castbar.transform.position = new Vector3 (castbar.transform.position.x - rate,castbar.transform.position.y,castbar.transform.position.z);
// castbar.transform.position = Vector3.Lerp(startpos,endpos, 0.5f);
}
}
}
}

