Skip to content
Advertisement

Function name not defined error when i try to use recursion

I want to make a player that can shoot bullets. To do this i tried defining a shoot function that gets called when space bar is pressed. The function looks like this (p is the player object btw):

JavaScript

I was hoping that the function would keep calling itself and the bullet would keep moving forward. However what actually happens is when i press space, it gives me an error

JavaScript

How i called the function:

JavaScript

Something i observed is that if i remove the recursion shoot() at the end of the shoot() function, it runs but the bullet stays in the same place as long as the space is being held down(as expected as recursion was removed). How can i fix this problem? Thanks

Advertisement

Answer

shoot is not a function, strictly speaking. It’s an instance method, and must be invoked from a bullet object. You need to use

JavaScript

for recursion.

However, this is a poor way to keep the bullet moving. This is a job for a loop. Recursion is best used when you’re calling the routine with a smaller version of the problem; this is just a continuance.

JavaScript

This raises the question of how you intend to quit moving the bullet. You need something like

JavaScript

Where x/y_limit are the upper bounds in that movement direction.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement