General programming question C# Unity
Hello everyone! I had a question that i kept asking myself and could never figure a proper way to do this.
What i want to happen is something like this.
-User presses key once – An object moves from one spot to another using Vector3.Lerp Vector3.Lerp requires it to be repeated either in the update method or some other way. I was wondering what the most efficient way i could make this happen with just one button press and not have to hold down the button.
Thanks in advance to everyone! Happy developing!
for lerp you need to calculate the alpha. when you use $$anonymous$$ovePosition you just use the speed as last parameter, so that's easier.
furthermore, just change the target position on press and just run $$anonymous$$ovePosition in Update. if target is the same position at the beginning as the object's, it won't move. as soon as target changes, it moves there. this makes it easy to just set different target positions.
Answer by SohailBukhari · Mar 30, 2017 at 08:35 AM
if you don't want to move in update or not want to press the button to move,then there is a simple way of moving object.
Make a thread to move object.
Make Two points to move from one point to other.
Time For moving object to destination.
class MyClass: MonoBehaviour {
[SerializeField]private Vector3 _pointBVector3;
private void Start()
{
var pointAVector3 = this.transform.position;
StartCoroutine(MoveObject(this.transform,pointAVector3,_pointBVector3,Random.Range(2f,5f)));
}
/// <summary>
/// MoveObject
/// </summary>
/// <param name="_transform">Pass transform Which You Want To Move</param>
/// <param name="initialPos">Start Position Of Move Object</param>
/// <param name="endPos">PointB </param>
/// <param name="time">Random Time Like Random.Range(2f,5f)</param>
/// <returns></returns>
private IEnumerator MoveObject(Transform _transform,Vector3 initialPos,Vector3 endPos,float time)
{
var i = 0.0f;
float rate = 1.0f / time;
while (i < 1.0f)
{
i += Time.deltaTime * rate;
_transform.position = Vector3.Lerp(a: initialPos, b: endPos, t: i);
yield return null;
}
}
}
Your answer
Follow this Question
Related Questions
Change the color of material based on percentage of health remaining 1 Answer
fixing rpc 0 Answers
Speeding up load time 0 Answers
adding two integers together once every half second,adding two integers together with delay? 1 Answer
XBox one controller only returning -1 or 1 for right analog stick. 0 Answers