Reputation: 1530
I have a script that is supposed to make a coin in the air to float up and down.
float increment = Mathf.Sin(startTime + Time.time * speed) * strength * Time.deltaTime;
Vector3 pos = new Vector3(this.transform.position.x, this.transform.position.y + increment, this.transform.position.z);
this.transform.position = pos;
It seemingly works, but it should only update the Y position. Now it also modifies the X and Z positions, but only so little that it's only noticeable when the game has been running for many minutes.
Is Unity making conversions of roundings inside Vector3? The position.x and position.z are not modified in any way, but the object is still sloooowly moving away.
Upvotes: 0
Views: 355
Reputation: 111
Why:
transform.position
is a world position of the object, that means it includes all transformations of it's parents up to the root and this is re-calculated each time you change the transform.position
. It's not stable when any of the parent objects has a non-default rotation (probably due to rounding errors in matrix/quaternion calculations).
Solution:
Storing the initial transform.position
(i.e. in Start
method) and modifying it's y
component will work but with a side-effect: transformations of any of it's parents will be lost. That could or could not be what somebody wants. If we do want to preserve parents' transformations (i.e. the platform with the coin moves) we should store and use transform.localPosition
.
Upvotes: 1