Move object based on local direction

Hello all,

I am trying to create a door script. I have three door wings. The upper one is working fine, the ones on the side not. They are moving in the wrong direction:

This is my code:

void Awake()
{
    leftWing = transform.Find("Firedoor_2_Left_wing");
    leftStartPosition = leftWing.localPosition;
}

private void Update()
{
    Vector3 leftTargetPosition = leftStartPosition + leftWing.right * 1.7f;
    leftWing.localPosition = Vector3.MoveTowards(leftWing.localPosition, leftTargetPosition, speed);
}

What am I doing wrong?

Thank you
Huxi

2 Answers

2

Just a note that might be useful :

  • tranform.right , transform.forward , tranform.up represent the direction of a certain object in world space , (aka the red , blue , green arrows in Local mode in scene view)

Now with that out of the way , look at this line

Vector3 leftTargetPosition = leftStartPosition + leftWing.right * 1.7f;

You’re saying here

I’m at position A compared to my parent , and i want to move X units to the right from the perspective of the world (as if i was placed directly in the scene as root object)

It just doesn’t make sense (at least without converting from one space to another) , you’re mixing points from different spaces (local and world).

That red arrow in local space is simply (1,0,0) aka Vector3.right , think about it , no matter how you turn IRL, you’re right hand is on your right , it’s local to you.
So since you’re doing your movement in local space , just change this to

Vector3 leftTargetPosition = leftStartPosition - (Vector3.right * 1.7f);

Ok, that works, I am surprised, that brackets have such an impact here. I mean, the multiplication is done at first anyway, so why are them even important? But good to know. Thank you :slight_smile: