- Home /
Scaling Canvas (or panel) and then trying to move a gameobject (child) attached to it
Need some help, think I back myself into a corner: I have a Canvas (and panel) set to World Space and disabled until the UI is needed. When it's needed, it's enabled and then gameobjects are added to it as children and displayed correctly (in a loop they are all added to the middle of the screen, scaled up, and rotated and can be seen in the game view. Everything is fine up until this point..
When I try to move the children, things go crazy and I finally realized my Canvas is scaled to .02, .02, .02 and the panel is scaled to .6, .6, .1 If I try this:
function FindHandandMove(){
var hand1 = GameObject.Find("Hand 1");
var pos1 = Vector3(280, 380, -1);
hand1.transform.position = pos1;
}
(or iTween.MoveTo(hand1,pos1, 0);)
The position it goes to is 19021.67, -211.67, -37900
Is there a way to correct this and keep the current Canvas/Panel scales?
Answer by adamk33n3r · Oct 11, 2017 at 04:21 AM
After coming back to my project after a time, I discovered that I figured out a solution for this problem.
When setting your positions you need to scale it by the transforms localScale.
var hand1 = GameObject.Find("Hand 1");
var pos1 = new Vector3(280, 380, -1);
hand1.transform.position = Vector3.Scale(pos1, this.transform.localScale);
And if you want to position things with relative coordinates to the parent, you need to divide by the scale beforehand.
var hand1 = GameObject.Find("Hand 1");
var pos1 = new Vector3(
280 + this.transform.position.x / this.transform.localScale.x,
380 + this.transform.position.y / this.transform.localScale.y,
-1
);
hand1.transform.position = Vector3.Scale(pos1, this.transform.localScale);
Hopefully this helps you or others finding this question!
Note: The code examples are in C# so you may or may not have to modify them.
Your answer
Follow this Question
Related Questions
Screen to canvas space 2 Answers
UI scaling issues 2 Answers
Scaling a menu bar 1 Answer
Keep the size of a gameobject on HUD changing Z depth 0 Answers
UI Animation Not Playing 1 Answer