Skip to main content
gamedev.net
🔒 Locked

Assigning one function to another?

Started by Abort_Retry_Fail Jun 3, 2002 at 7:28 PM 3 replies 400+ views
Original Post
Abort_Retry_Fail
Abort_Retry_Fail
Hi, I''m starting an RPG battle system. When an action is chosen during combat, the appropriate move function is performed after "switch-caseing" the index of the action selected. Ex. switch(index) { case ATTACK: DoAttack(); break; case DEFEND: Defend(); break; } However, with this system I have to re-determin the selection every frame. I thought up a possible solution, but I''m not sure how to execute it. My character class has a function called Action(). Can I assign this function to another particular function? That is, make the character''s Action() function point to the appropriate function (such as Attack() or Defend()) and just call character.Action() each frame instead of re-determining the chosen move every frame?
merowe
merowe
Are you doing this using OOP? If so, you can use something called virtual functions to do exactly what you are looking for. If you are just using straight C code, you can create a function pointer called Action, but you still will have to have a switch statement to update the function pointer (so that will not do what you are looking for).
bdc256
bdc256
use a pointer to a function
such as
viod (*pfunc)();
that would point to a function that returns void and takes no paramiters just add paramiters inside the () at the end the way you would the funtion you want it to point to

change void to the return type you want

all possible funtions attack() defened() should accept same number of paramiters and return same type

Fruny
Fruny

  
typedef void func(void);

void Attack1() { /*...*/ };
void Attack2() { /*...*/ };
void Attack3() { /*...*/
};

func* AttackTable[3] = { Attack1, Attack2, Attack3 };

...

func* MyAttack = AttackTable[2];

...

MyAttack();


Before you ask, this does not easily map to (non-static) class member functions, because pointers to (non-static) member functions are not pointers (they are ''pointer-to-member''s).

Go to function-pointer.org for more details.
Go to Boost for an object-oriented solution.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Abort_Retry_Fail
Abort_Retry_Fail
Thanks for the great replies! I''d heard of function pointers before, but never looked into them...

Topic Locked

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

Sign in to reply to this topic.