c# – How to move object on local space not object space in unity


transform.Translate does something a little funny. The Space you select picks the directions that it moves the object, but doesn’t scale the translation. The actual translation vector is always applied in worldspace, and you’re just selecting whether to rotate the direction to match the object’s local axes, or not.

Since an object might not have a parent at all to fetch a direction from, I’m guessing they skipped the extra conditional logic for this case because it doesn’t come up in practice much that you want to move an object with respect to its parent while ignoring its parent’s scale. More often, if we’re doing parent-space positioning, we want to use something like:

transform.localPosition += translation;

which allows the parent’s scale to affect the resulting position.

But, if you really want transform.Translate style behaviour and syntax for this case, we can add it as an extension method:

public enum Spaces {
    World,
    Parent,
    Self
}

public static class SpaceExtension {

    public static void Translate(this Transform transform, Vector3 translation, Spaces ralativeTo) {
        switch(relativeTo) {
          case Spaces.World: 
              transform.position += translation;
              break;
          case Spaces.Self:
              transform.position += transform.rotation * translation;
              break;
          case Spaces.Parent:
              // Fall back on world space if there's no parent.
              Quaternion rotation = Quaternion.identity;
              if(transform.parent != null)
                   rotation = transform.parent.rotation;
              transform.position += rotation * translation;
              break;
        }
    }
}

This gives you a new overload of transform.Translate to use if you like, with the alternative Spaces enumeration to pass the parent space option.

I haven’t tested it extensively to verify whether it handles non-uniform scales the same way the original transform.Translate does, though I’d caution that if you’re using non-uniform scale in a parent hierarchy you’re likely going to run into bigger troubles. 😉



Source link

More To Explore

Share on facebook
Share on twitter
Share on linkedin
Share on email