- Home /
How does vector multiplication and position updates work in unity?
This piece of code involves the multiplication of a Vector3 moveVector with a float moveSpeed and another float, Time.deltaTime. do these floats get multiplied to every value of the Vector3 (x, y, z)? Furthermore, if I write transform.position instead of GameObject.transform.position, am I right that the transform.position transforms the position of the global object, thereby updating the position of whatever GameObject/prefab this movement script is attached to?
void Move(Vector3 desiredDirection)
{
moveVector.Set(desiredDirection.x, 0f, desiredDirection.z);
moveVector = moveVector * moveSpeed * Time.deltaTime;
transform.position += moveVector;
}
Answer by Namey5 · Oct 16, 2020 at 11:35 AM
Correct - multiplying a vector by a scalar is equivalent to multiplying each individual component by that scalar, i.e;
//where:
// - a : Vector3
// - b : float
a *= b;
//is the same as
a = new Vector3 (a.x * b, a.y * b, a.z * b);
As for transform.position vs gameObject.transform.position - they are both identical. 'transform' is a property (variable that acts like a function) that just points to the transform attached to the current object instance and is present in both the GameObject class and anything that inherits from Component (i.e. any script). In fact, position is also a property, which is why if you tried to use 'transform.position.Set (x,y,z)' it wouldn't work.
The 'position' property acts like two different functions - when you 'get' the value from it, it runs a function that creates a new Vector3 and copies data out of the object's transformation matrix. When you 'set' it to a value, it runs another function that takes a Vector3 and modifies the transformation matrix. If you were to call 'transform.position.Set(x,y,z)' it would make a new variable and you would only set the values to that new variable without updating the original transform.