Skip to main content
GameDev.net gamedev.net
🔒 Locked

animate( )...not working?

Started by lack the hack Apr 3, 2006 at 10:29 PM 0 replies 750+ views
Original Post
lack the hack
lack the hack
hey, i'm making a simple physics engine and stuff, and when i try to make an animate function, for some reason it doesn't animate. here's the code:

CVector position1 = CVector(-5,-5,0);
CVector velocity1 = CVector(10,10,0);
CVector acceleration1 = CVector(0,-9.8,0);
void animate(float deltaTime, CVector position,CVector velocity,CVector acceleration)
{
	position += velocity * deltaTime;
	velocity += acceleration * deltaTime;
}
and in my loop, here's how i call it:

animate(newDeltaTime,position1,velocity1,acceleration1);
and that's it. when i have just deltaTime as an argument it works, but i want this to work for whatever position i want, not just for one vector. any reason to see why it's not working? thanks --nathan
Auron
Auron
It doesn't work because you're passing in the parameters by value, and so the function uses local copies of the parameters and never changes the originals. To fix this, you can either use pointers or references, like so:

With pointers:
void animate(float deltaTime, CVector *position,CVector *velocity,CVector acceleration){	(*position) += (*velocity) * deltaTime;	(*velocity) += acceleration * deltaTime;}//call it like thisanimate(newDeltaTime,&position1,&velocity1,acceleration1);


With references:
void animate(float deltaTime, CVector &position,CVector &velocity,CVector acceleration){	position += velocity * deltaTime;	velocity += acceleration * deltaTime;}//call it like thisanimate(newDeltaTime,position1,velocity1,acceleration1);


Notice the difference in semantics here. The references version only requires you to change the function's parameters, and avoids the nasty situation where a potentially null pointer gets passed in.

Of course, this is all assuming that you're using C++ and not C# or Java (which both would have worked properly with the original code anyway).

-Auron

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.