Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Moving Gameobjects - Questions

Discussion in 'Getting Started' started by Sacraanima, May 21, 2018.

  1. Sacraanima

    Sacraanima

    Joined:
    Aug 28, 2017
    Posts:
    2
    Hey Guys,

    im building a game and its goal is to travel a distance and avoid obstacles on the way.
    Now i am looking for a solution to make a moving ostacle.

    The obstacle needs to travel the distance between "x -7" to "x 7"and back in repeat.

    I try to do this with a little C# script that looks like this:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Push : MonoBehaviour {
    4.  
    5.     public Rigidbody rb;
    6.     public float PushForce = 200f;
    7.     public Transform position;
    8.  
    9.     // Update is called once per frame
    10.     void Update ()
    11.     {
    12.  
    13.         if (position.position.x == 7.00)
    14.         {
    15.  
    16.             rb.AddForce(-PushForce * Time.deltaTime, 0, 0);
    17.  
    18.         }
    19.  
    20.         if (position.position.x == -7.00)
    21.         {
    22.  
    23.             rb.AddForce(PushForce * Time.deltaTime, 0, 0);
    24.  
    25.         }
    26.     }
    27. }
    28.  
    But its dont work for me. The script doesnt notice if the obstacle access the point of return...

    What i am doing wrong and do you know a other way to solve the problem ?

    (I guess ich dont have to say im pretty new to this world)
    (also dont mess with me because my english isnt good)

    Thanks for your help =)
     
  2. chelnok

    chelnok

    Joined:
    Jul 2, 2012
    Posts:
    680
    When comparing floats like that you shouldn't use equal == because the value most likely is something like 7.000021 or 6.9999994 at the frame you expecting it to be 7.00 or -7.00

    So in this case use <= and >=

    Code (CSharp):
    1.     void Update ()
    2.     {
    3.         if (position.position.x >= 7.00)
    4.         {
    5.             rb.AddForce(-PushForce * Time.deltaTime, 0, 0);
    6.         }
    7.         if (position.position.x <= -7.00)
    8.         {
    9.             rb.AddForce(PushForce * Time.deltaTime, 0, 0);
    10.         }
    11.     }
     
  3. Sacraanima

    Sacraanima

    Joined:
    Aug 28, 2017
    Posts:
    2
    Works fine after disable gravity =)

    Thanks alot