Search code examples
c#unity-game-engineqvector3d

Unity3D Vector 3 Teleporting


image

Hey Folks!

I attached an image to visualize my explanation of the problem i have. In my game, there is a green ball rolling along an endless road, getting chased by a yellow ball. To make the road seem endless, the ball gets teleported back (purple line on the bottom image), when it crosses a certain distance on the x-axis (purple line on the top image). I did it like this:

if (gameObject.transform.position.x <= -20) {
    gameObject.transform.position = new Vector3 (transform.position.x + 80, transform.position.y, transform.position.z);
}

and it works totally fine.

When the green ball is getting „teleported“, the yellow ball should get teleported back with the same value, so the distance between the too balls doesn’t change after teleporting. So I made a public game object „enemy“, placed the yellow ball inside the enemy field in the inspector and changed the code to this:

if (gameObject.transform.position.x <= -20) {
    gameObject.transform.position = new Vector3 (transform.position.x + 80, transform.position.y, transform.position.z);
    enemy.transform.position = new Vector3 (transform.position.x + 80, transform.position.y, transform.position.z);
}

But as you can see on the bottom image, the yellow ball wasn’t teleported on the same distance. It seems like the distance is added from it’s original starting point and not from the point it had before teleporting. Hope you guys know a solution for this.

The Yellow Ball has a script to follow the Player, maybe it has to do something with this?

void Update ()
{

    //enemy follows the ball with speed 8
    transform.LookAt (target);
    transform.Translate (Vector3.forward * 8 * Time.deltaTime);

    //fix y-position
    Vector3 tmp = transform.position;
    tmp.y = lockedY;
    transform.position = tmp;

}

Solution

  • You want to move the enemy back 80 units, then you need to move the enemy back 80 units.

    enemy.transform.position = new Vector3(enemy.position.x + 80,enemy .position.y,enemy.position.z);