How do I pass a function as a parameter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I pass a function as a parameter

I have a class called RigidBody and it has an update function. And in there you shift the horizontal axis and a function is called to handle and check horizontal collisions and the same for the vertical axis. Now each entity that has a RigidBody component has a custom handleHorizontalCollisions() and handleVerticalCollisions() which I will need to pass in. How do I pass functions? Here is what I am trying to do: By the way “dt” stands for delta time. My game is not frame capped. And “Velocity” is a member of RigidBody. public void update(float dt, Vector position, function handleHorizontalCollisions, function handleVerticalCollisions) { position.x += velocity.x * dt; handleHorizontalCollisions(); position.y += velocity.y * dt; handleVerticalCollisions(); }

10th Jan 2021, 6:07 PM
Frumkin
Frumkin - avatar
2 Answers
+ 3
Frumkin You can not pass a function as a parameter in java. You can just call the function inside another function using object. That's why Java is object oriented programming language.
10th Jan 2021, 6:25 PM
A͢J
A͢J - avatar
0
+ For simpler functions is sometimes better to use lambda expressions as parameter. Also there is complicated way how to invoke Method object by the reflect API.
11th Jan 2021, 11:29 AM
zemiak