I'm working on a game and using Vector2List to represent the positions of many particles. Let's say I want to increase the X value by 4.
When I use a single Vector2 I can do something like this and everything goes fine:
position.x += 4;
Where position is an instance of Vector2
If Vector2 was {3, 5} then it becomes {7, 5} (everything is OK).
But if I'm using a vector list, I would do something like:
position[i].x += 4
Where i is the particle index and position is an instance of Vector2List
Then it goes from {3, 5} to {3, 5} (no change at all!).
The only way I found to get this done was using the function set values, but it doesn't look like it should be mandatory. Am I doing something wrong?
What is NOT working
position[i].x += 4;
What is working
position.setValues(i, position[i].x+4, position[i].y);
Sample code
Vector2List positions = Vector2List(1);
print('positions[0] = ${positions[0]}');
positions[0].x += 4;
positions[0].y += 10;
print('positions[0] after operation = ${positions[0]}');
positions.setValues(0, positions[0].x + 4, positions[0].y + 10);
print('positions[0] after setValues = ${positions[0]}');
The result is
I/flutter (32638): positions[0] = [0.0,0.0]
I/flutter (32638): positions[0] after operation = [0.0,0.0]
I/flutter (32638): positions[0] after setValues = [4.0,10.0]
My software
Flutter version Channel Stable 2.0.1
Dart SDK version: 2.12.0 (stable)
I'm using null safety.
Please forgive any English mistake, I'm not a native speaker.
Thanks!
The problem is how the []
operator is implemented for Vector2List
:
T operator [](int index) {
final r = newVector();
load(index, r);
return r;
}
As you can see, it will actually create a new vector object and return this after it is filled with data. This means any modifications to this new vector object does not result in any change in the Vector2List
object.
What you can do is something like this:
import 'package:vector_math/vector_math_lists.dart';
void main() {
Vector2List positions = Vector2List(1);
print('positions[0] = ${positions[0]}');
positions[0] = positions[0]
..x += 4
..y += 10;
print('positions[0] after operation = ${positions[0]}');
// positions[0] after operation = [4.0,10.0]
}
It is still not great, but does the same that you do but more simplified. The most optimal way I think is to create a new Vector2
and use it with the +=
operator on Vector2List
:
import 'package:vector_math/vector_math.dart';
import 'package:vector_math/vector_math_lists.dart';
void main() {
Vector2List positions = Vector2List(2);
print('positions[0] = ${positions[0]}');
positions[0] += Vector2(4, 10);
print('positions[0] after operation = ${positions[0]}');
// positions[0] after operation = [4.0,10.0]
}