0
\$\begingroup\$

I have a RectTransform Button that i want to make it move to a de-terminated vector3.

To move the button i use this code (it is inside Update())

        int i = -1;
        foreach (RectTransform Button in Buttons)
        {
            i++;
            Vector3 NewPosBtns = new Vector3(StartButtonsVect[i].x, (StartButtonsVect[i].y + 192.5f), StartButtonsVect[i].z);
            Vector3 CurPosBtns = StartButtonsVect[i];
            Button.localPosition = Vector3.MoveTowards(CurPosBtns, NewPosBtns, AnimationSpeed);
        }

Buttons is a array and i add the button to the list using unity editor

StartButtonsVect is of vector3 that i add the using this code

void Start()
{
    foreach (RectTransform Button in Buttons)
    {
        StartButtonsVect.Add(Button.localPosition);
    }
}

For some reason the button start shaking instead of going to the target position (NewPosBtns)

\$\endgroup\$
1
\$\begingroup\$

The first argument of MoveTowards is the current position of the object.

You've passed a variable called CurPosBtns, which might imply it's "current", but you initialized that variable to StartButtonsVect[i]. Which means despite its name, it's still representing the start position of the button, not the current position.

This means that every frame, MoveTowards thinks it's starting from scratch - it never has a chance to accumulate any progress because you always pass it the start position. So you only see one frame's worth of movement progress - which will wiggle back and forth based on frame timings (fast frames make very little movement progress, assuming you've scaled AnimationSpeed by Time.deltaTime).

The fix is to replace CurPosButns with the actual position, ie.

Button.localPosition = Vector3.MoveTowards(Button.localPosition, NewPosBtns, AnimationSpeed);

Also, for positioning elements on a canvas, consider using anchoredPosition rather than localPosition. This tends to play nicer with UI layout and scaling behaviours.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.