- Home /
Making an object bounce, using Mathf.Lerp
Hi there,
I'm trying to make an object (fireball) bounce between -4 and 10 on the Y Axis, without Rigidbody, and such. Instead, the object gets stuck on the exact same position.
void Update () {
if (transform.position.y == -4) {
transform.position = new Vector3(transform.position.x,Mathf.Lerp(min,max,Time.time),transform.position.z);
}
if (transform.position.y == 10) {
transform.position = new Vector3(transform.position.x,Mathf.Lerp(max,min,Time.time),transform.position.z);
}
}
I suspect the "==" causes the trouble, but ">" and "<" cause other problems.
Just as a side note, you don't have to go:
transform.position = new Vector3(transform.position.x, value, transform.position.z);
You can simply go:
transform.position.y = value;
It's much easer, much nicer and also faster :)
& on a side note, to the side note, totally wrong and misleading post. If you look at the syntax you will see it is written in C#, not JS. In C# you can't edit directly into vector3 components, but you need to re-create the vector3 and feed it back in, so no. Also as far as faster goes, when the variable type is a vector3, it has to re-create the entire vector3 anyhow, JS just hides this fact from you by doing it automaticly, so faster, that's another no. However, 'nicer', you can have that one.
Answer by robhuhn · Aug 06, 2013 at 11:46 AM
The position.y hits unlikely exactly -4 or 10. Using Mathf.PingPong could be what you are after:
void Update () {
transform.position = new Vector3(transform.position.x, Mathf.PingPong(Time.time * speed, 14) - 4, transform.position.z);
}
Another approach is using Mathf.Sin (returns -1 to 1) which gives an in/out easing.
void Update () {
transform.position = new Vector3(transform.position.x, Mathf.Sin(Time.time * speed) * 7 + 3, transform.position.z);
}