Search Unity

If I have X and Y final position values, how do I move a 3d object up/right locally?

Discussion in 'Scripting' started by astracat111, May 25, 2022.

  1. astracat111

    astracat111

    Joined:
    Sep 21, 2016
    Posts:
    725
    So say I have X and Y final position values. Let's take for example X = 1f and Y = 2f.

    Right now I have code in a custom script that has this:

    Code (CSharp):
    1. transform.localPosition = Vector3.SmoothDamp(transform.localPosition, new Vector3(finalPos.x, finalPos.y, transform.localPosition.z), velocity, posTime);
    This works fine for a 2d camera, but when applied to 3d it moves it only along the X and Y axis in world space.

    I understand that we have this:

    Code (CSharp):
    1. transform.Translate(startPos,endPos);
    And I understand that there's:

    Code (CSharp):
    1. transform.right
    And:

    Code (CSharp):
    1. transform.up
    I feel like all the elements needed are here...but I can't figure it out right now how to move the 3d object along it's local X and Y coordinates in world space, in other words it'll probably take translating what's there....finalPos.x and finalPos.y into a translated 3dobjfinalPos.x, 3dobjfinalPos.y and 3dobjfinalPosz...

    So I guess I'm looking at how to translate a Vector2 x and y 2d movement (final pos I mean) into a Vector3 final pos that's along the 3d object's x, y, z axis.

    In other words, just simply move the 3d camera right, up, down, left with no moving it forward and back in 3d space.

    Any help would be greatly appreciated.
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    This isn't correct. Translate moves in a relative motion, it doesn't accept two positions at all: https://docs.unity3d.com/ScriptReference/Transform.Translate.html

    Look at the above link, the second argument is the space to move in which by default is the local space. Local space means just that, local so you can pass in Vector3.Left/Right and Vector3.Up/Down etc.

    Unless I'm mistaken in what you're asking i.e. how to move in the local-space of the Transform?

    If you want world-space then select the world space option above: https://docs.unity3d.com/ScriptReference/Space.html
     
    Bunny83 likes this.