Search code examples
c#unity-game-enginegame-physicsparallax

Moving and teleporting an object in the x direction forever


So I have had this problem that has been frustrating me for a while, I need to get 3 game objects to move at %speed of a base set speed. That part is easy. Now the problem is that i just cannot get it to move to a set position, then teleport infront of me and continue, Help would be much appreciated!

What I'm going for

Current code

Update function

    void Update()
{
    //suuuuper bad implemantation
    float newPos = Mathf.Repeat(Time.time * globalspeed, 20);
    Ground1.transform.position = startpos + new Vector2(reset, upPos1) * newPos * Ground1Speed;
    Ground2.transform.position = startpos + new Vector2(reset, upPos2) * newPos  * Ground2Speed;
    Ground3.transform.position = startpos + new Vector2(reset, upPos3) * newPos * Ground3Speed;

}

Solution

  • I'm not sure I understand what you want but if I'm right, you want 3 game objects to move on the ground (like a driving car) and disappear when they get to the end, then appear in the start position and move again in infinite loops. If I'm right you should try this:

    public float objectSpeed;
    
    void update()
    {
        MoveObject();
    }
    
    void MoveObject()
    {
    
        objectSpeed = 20; //Set the object speed
        
        if (transform.position.x >= 120) //Set the position to where you want your object to disappear
        {
            disapper(gameObject);
        }
    
        if (transform.position.x >= 300) //This position is related to when the object will appear again in the start position
        {
            appear(gameObject);
        }
        
        void disappear()
        {
            transform.Find(gameObject).GetComponent<MeshRenderer>().enabled = false;
        }
    
        void appear()
        {
            transform.Find(gameObject).GetComponent<MeshRenderer>().enabled = true;
        }
    } // Drag this script to 3 of the game object you want them to move. This code is no tested but should work fine.