Skip to content

Instantly share code, notes, and snippets.

@nicloay
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save nicloay/111be7be0a1e7f591247 to your computer and use it in GitHub Desktop.

Select an option

Save nicloay/111be7be0a1e7f591247 to your computer and use it in GitHub Desktop.
Kinetic test at unity3d - apply initial forces and stop rigidbody2d at random time
using UnityEngine;
using System.Collections;
using UnityTest;
/// <summary>
///
/// Kinetic test.
///
/// some usefull info here http://www.moaisnippets.info/using-box2d-impulses-to-move-objects
/// impulse = mass * velocity;
///
/// you have to use ForceMode2D.Impulse to apply impulse to the body.
/// ForceMode2D.Force - assume you apply impulse at FixedDeltaTime amount of time
/// </summary>
public class KineticTest : MonoBehaviour {
public Vector2 StartForce = new Vector2(1000,0);
public float TestTimeoutMin = 0.5f;
public float TestTimeoutMax = 0.7f;
// Use this for initialization
public float FloatEpsilon = 0.01f;
IAssertionComponentConfigurator startSpeed;
IAssertionComponentConfigurator endSpeed;
void Awake(){
FloatComparer startAbsSpeed = AssertionComponent.Create<FloatComparer>(out startSpeed, (UnityTest.CheckMethod)0, gameObject, "Rigidbody2D.velocity.x", 0.0f);
startAbsSpeed.floatingPointError = FloatEpsilon;
startAbsSpeed.compareTypes = FloatComparer.CompareTypes.Greater;
FloatComparer endAbsSpeed = AssertionComponent.Create<FloatComparer>(out endSpeed, (UnityTest.CheckMethod)0, gameObject, "Rigidbody2D.velocity.x", 0.0f);
endAbsSpeed.floatingPointError = FloatEpsilon;
endAbsSpeed.compareTypes = FloatComparer.CompareTypes.Equal;
}
void Start(){
StartCoroutine(DoStart());
}
IEnumerator DoStart () {
float velocityX;
yield return new WaitForSeconds(0.1f);
rigidbody2D.AddForce(StartForce);
yield return new WaitForSeconds(Random.Range(TestTimeoutMin, TestTimeoutMax));
velocityX = rigidbody2D.velocity.x;
float impulseX = velocityX * rigidbody2D.mass;
Assertions.CheckAssertions(startSpeed as AssertionComponent);
rigidbody2D.AddForce(new Vector2( -impulseX, 0.0f), ForceMode2D.Impulse); //try Force it won't work
yield return null;
Assertions.CheckAssertions(endSpeed as AssertionComponent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment