Move Object in unity using its local space.

I have a simple script that moves the cube left and right. When the object is aligned in with global coordinates, it seems to work fine. But when I rotate the object by 90 degrees, it moves but the limiting conditions don’t work.

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

public class SwerveTest : MonoBehaviour
{
    public float speed;
    public float minX, maxX;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            if (transform.position.x>minX)
            {
                transform.Translate(Vector3.left * speed * Time.deltaTime, Space.Self);

            }
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            if (transform.position.x<maxX)
            {
                transform.Translate(Vector3.right*speed*Time.deltaTime, Space.Self);
            }
        }
    }
}

Hello.

I dont understand your problem, but i explain things:

First, Transform.translate is by default in Space.Self (using its own coordinates, so Vector3.forward is always where the object is facing) so you do not need to specify the Space.Self)

But transform.position is the Global object position in world space coordinates.

explica

So the coord system (self) of the object has changed, and its now different form World (global) coord system.

As you are using transf.posi.x as a condition (global/world), but changing the position using Translate (local/self) it will not mach. A solution? Move it wioth transform.position directly

Bye!