I have this code:
void OnCollisionEnter (Collision collision)
{
if (canCollide == true) {
canCollide = false;
ContactPoint contactPoint = collision.contacts [0];
GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
cube.transform.localScale = new Vector3 (5, 5, 5);
cube.transform.position = contactPoint.point;
iTween.MoveTo (cube, iTween.Hash (
"y", 40,
"time", 0.5));
iTween.MoveTo (cube, iTween.Hash (
"position", new Vector3 (55, 79, 10),
"time", 0.5f,
"delay", 0.5f,
"oncompletetarget", GameObject.Find ("PlayerCar"),
"oncomplete", "IncrementGauge"));
Destroy (cube, 1.1f);
}
}
This works ok, both animations are in sequence. But the sum of the times shoud be 1 second. But Destroy() cannot be delayed by 1 second, it has to be at least 1.1 second. Why? Can I somehow destroy the cube a bit faster and still have IncrementGauge() fired (1 second on Destroy, prevents firing IncrementGauge()).
Thanks.
This happens because the iTween library checks in every Update call if 1.0 second has passed, which can't be exactly 1.0 second because it depends on your framerate and floating point arithmetic is imprecise.
Your problem can be solved by destroying the cube and incrementing the gauge in the same callback method DestroyCubeAndIncrementGauge() passed into the parameteroncomplete
as string.
public class CollisionObject : MonoBehaviour
{
[SerializeField]
private bool canCollide = true;
void OnCollisionEnter(Collision collision)
{
if (canCollide == true) {
canCollide = false;
ContactPoint contactPoint = collision.contacts [0];
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localScale = new Vector3(5, 5, 5);
cube.transform.position = contactPoint.point;
iTween.MoveTo(cube, iTween.Hash(
"y", 40,
"time", 0.5));
iTween.MoveTo(cube, iTween.Hash(
"position", new Vector3 (55, 79, 10),
"time", 0.5f,
"delay", 0.5f,
"oncompletetarget", this.gameObject,
"oncompleteparams", cube,
"oncomplete", "DestroyCubeAndIncrementGauge"
));
}
}
public void DestroyCubeAndIncrementGauge(GameObject cube)
{
// destroy the cube
Destroy(cube);
// inform the PlayerCar to IncrementGauge
GameObject.Find("PlayerCar").SendMessage("IncrementGauge");
}
}