Search Unity

[SOLVED] Detect if an object no longer has any velocity on the y axis...

Discussion in 'Scripting' started by Etaodev, Dec 23, 2019.

  1. Etaodev

    Etaodev

    Joined:
    Dec 8, 2019
    Posts:
    13
    Hello,
    I want to test if an object no longer has any activity on its y axis, so that I can trigger a game over functionality.

    Basically, the object gets launched via a point effector. The object then bounces around, and when it no longer moves anymore on the y axis I want to Debug.Log("GameOver");

    I can only test whether if the object is not moving anymore on the y axis, not the x. Because I have a surface effector on the ground object that constantly pushes the object forward. Hence, I only want to test for if the velocity on the y axis == 0;

    Any ideas on how this can be achieved?

    Please help!
     
  2. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    976
    Code (CSharp):
    1. if(rigidBody.velocity.y <= 0)
    2.     DoStuff();
     
    Etaodev likes this.
  3. Emolk

    Emolk

    Joined:
    Feb 11, 2014
    Posts:
    241
    Needs to be:

    Code (CSharp):
    1. if(rigidBody.velocity.y == 0) {
    2.     DoStuff();
    3. }
    Objects moving backwards have negative velocity.
     
    Etaodev likes this.
  4. Etaodev

    Etaodev

    Joined:
    Dec 8, 2019
    Posts:
    13
    Thank you both for answering. I will try it out right now.
     
  5. Etaodev

    Etaodev

    Joined:
    Dec 8, 2019
    Posts:
    13
    I have tried both code in the gameobject, but the console shows the message even when the gameobject isn't stationary on the y axis.
     
  6. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    976
    Are you using RigidBody to move you objects? And not transform.
     
  7. Emolk

    Emolk

    Joined:
    Feb 11, 2014
    Posts:
    241
    Are you using physics forces?

    Try replacing rigidBody with 'GetComponent<RigidBody>()' or 'GetComponent<RigidBody2D>() if it has a 2D RigidBody.
     
  8. Etaodev

    Etaodev

    Joined:
    Dec 8, 2019
    Posts:
    13
    I ended up setting up a system where it tests for zero velocity in the update method, triggers a IEnumerator timer, and checks is the transform on the y is equal or less than that of the ground. And that worked! Thank you both for helping me. I'll mark this thread as solved.