Time for action – tweaking the bounce

Now that we can detect when the heart is hitting the tray, there's no end to the fun we can have! While we're in the code, let's make a quick change to make the gameplay slightly better.

  1. Double-click to open the HeartBounce script.
  2. Type the following at the top of the script:
    #pragma strict
    var velocityWasStored = false;
    var storedVelocity : Vector3;
    function OnCollisionEnter(col : Collision) {
      if(col.gameObject.CompareTag("tray")) {
        Debug.Log("yes! hit tray!");
        if (!velocityWasStored) {
          storedVelocity = rigidbody.velocity;
          velocityWasStored = true;
        }
        rigidbody.velocity.y = storedVelocity.y;
      }
    }

Save the script and test the game. You may not notice a difference at first, but we've made a clear improvement ...

Get Unity 4.x Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.