函数不会修改作为指针(或引用)传递的Struct对象



编辑:代码现在可以运行

因此,我正在尝试更新对象在结构中的位置,并测试了update和Rule函数中的代码,执行和Rule类中的局部变量都会按预期更改。不变的是Object类型的结构对象的成员变量。以下是我的cpp文件中的相关代码:struct对象{float x;浮动y;浮点vx;浮动vy;glm::vec4 v_Color;unsigned int id;

Object(float _x, float _y,
float _vx, float _vy,
glm::vec4 _v_Color, unsigned int _id)
{
x = _x;
y = _y;
vx = _vx;
vy = _vy;
v_Color = _v_Color;
id = _id;
}
}
std::vector<Object> red;
std::vector<Object> green;
std::vector<Object> blue;
std::vector<Object> yellow;
void Rule(std::vector<Object>* group1, std::vector<Object>* group2, float G)
{
float g = G;
for (int i = 0; i < group1->size(); i++) {
Object p1 = (*group1)[i];
float fx = 0;
float fy = 0;
for (int j = 0; j < group2->size(); j++) {
Object p2 = (*group2)[j];
float dx = p1.position.x - p2.position.x;
float dy = p1.position.y - p2.position.y;
float r = std::sqrt(dx * dx + dy * dy);
if (r < 80 && r > 0) {
fx += (dx / r);
fy += (dy / r);
}
}
p1.velocity.x = (p1.velocity.x + fx) * 0.5;
p1.velocity.y = (p1.velocity.y + fx) * 0.5;
p1.position.x += p1.velocity.x;
p1.position.y += p1.velocity.y;
if ((p1.position.x >= 800) || (p1.position.x <= 0)) { p1.velocity.x *= -1; }
if ((p1.position.y >= 700) || (p1.position.y <= 0)) { p1.velocity.y *= -1; }
std::cout << "Calculated velocity: " << fx << ", " << fy << std::endl; // these numbers will change
(*group1)[i] = p1;
std::cout << "ID: " << p1.id << ", " << "Velocity " << p1.velocity.x << ", " << p1.velocity.y << "Position: " << p1.position.x << ", " << p1.position.y << std::endl; // you will see these values do not change
}
}
std::vector<Object> CreateObjects(unsigned int number, glm::vec4 color)
{

std::vector<Object> group;
for (int i = 0; i < 10; i++) {
float x = rand() % 750 + 50;
float y = rand() % 550 + 50;
Object o(x, y, 0, 0, color, objects.size());
group.push_back(o);
objects.push_back(o);
}
return group;
}
void main()
{
yellow = CreateObjects(10, glm::vec4(1.0f, 1.0f, 0.0f, 1.0f));
blue   = CreateObjects(10, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f));
green = CreateObjects(10, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f));
red = CreateObjects(10, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f));
Rule(&green, &green, -0.32);
Rule(&green, &red, -0.17);
Rule(&green, &yellow, 0.34);
Rule(&red, &red, -0.1);
Rule(&red, &green, -0.34);
Rule(&yellow, &yellow, 0.15);
Rule(&yellow, &green, -0.2);
Rule(&blue, &green, -0.2);
}

编辑:代码现在应该可以运行

您应该调试程序,看看程序在哪个步骤中的行为与预期的不同

指向std::vector的指针实际上修改了对象。如果在对象结构中添加另一个字段int计数器,您应该会看到它

struct Object
{
glm::vec3 position;
glm::vec3 velocity;
glm::vec4 v_Color;
unsigned int id;
int counter;  // dont forget to initialise it in Object constructor

这里是

void Rule(std::vector<Object>* group1, std::vector<Object>* group2, float G) 

只需添加

p1.counter += 1;

要么你真的修改了值,但没有注意到它。要么你有某种错误。可能是glm::vec3字段x和y应该以另一种方式修改,而不是glm:;vec3::x+=val

第S页一些来自互联网的消息来源说,你可以访问vec3 cooridates,但不能更改它们。看起来像你的

https://www.reddit.com/r/cpp_questions/comments/60nsl5/accessing_the_x_y_and_z_values_of_a_vec3_position/

最新更新