Gameobject don't move for a certain distance after rotation

Hi all! Hope this is the right section of the forum. I’m trying to create a moving platform that moves back and forth on Z axes and it correctly does. But, when i rotate the gameobject, for example 90 degrees, it will not anymore come back. Hope you can help me. This is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SlidingMovement : MonoBehaviour
{
    public enum LeftOrRight {
        Left = -1, Default = 0, Right = 1
    }

    private float speed = 4.0f;
    private Vector3 start_position;
    private LeftOrRight platformDirection = LeftOrRight.Default;
  
    // Start is called before the first frame update
    void Start()
    {
        this.platformDirection = LeftOrRight.Right;
        this.start_position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += transform.forward * (int)platformDirection * speed * Time.deltaTime;
        if(transform.position.z - start_position.z >= 10.0f) {
            SwitchDirection();
        } else if (transform.position.z - start_position.z <= -10.0f ) {
           SwitchDirection();
        }
    }

    private void SwitchDirection() {
        if (this.platformDirection == LeftOrRight.Right)
        {
            this.platformDirection = LeftOrRight.Left;
        } else
        {
            this.platformDirection = LeftOrRight.Right;
        }
    }
}

transform.forward basically gives a vector in direction of rotation of gameobject.

Vector3.forward is a new Vector3 (0, 0, 1);

Your script basically makes the platform move forwards and backwards, using transform.forward.

When you rotate the platform, it’ll still move backwards and forwards(like how when walking if you turn right, you’re still walking forwards according to your view)

But you prob. understand that.

Second issue: if transform.position.z >= start.position.z, switch directions.

That’s all well and good, until you rotate your platform. Then your platform no longer moves in z direction, but rather in x-direction.

Your platform can move 100000000 units in x-axis, and still have ~same z coordinates as your start position.

Do you change your script every time you rotate your platform? No. Just take transform.position -start.position, and use like .magnitude to find the distance between the two.

:slight_smile: