Basically I am making a game where the enemy comes after the hero when He is in sight. What I do to achieve this is
var distx = hero.px - px;
var disty = hero.py - py;
moveX += distx * .00005;
moveY += disty * .00005;
Now I had to multiply it by .00005 because anything higher, makes him come up on the hero pretty quick. I want the enemy to move slow so I multiplied it by .00005. My problem is the farther the distance they are, the faster the monster moves which makes it harder for the hero to get away. I know why this is, I just need to know how to resolve it.
I develop the game where if the monster is too far away, i remove him from the stage. but the problem is getting away. I want him to move at a constant speed no matter how far apart they are.
I also want to achieve this by not using any class properties. (i.e I want all varibles to be local). This method is in a loop as well
What am I doing wrong? and what are solutions.
Thanks guys
All you have to do is rate limit the velocity of the enemy.
You have essentially implement only the “proportional” part of what control systems engineers (1) call a PID controller. Your desire is for the enemy to track the player, and the PID controller is a nice simple
tunable(think enemy difficulties) tracking controller.In a tracking PID controller, you first measure the error between your desired goal and the current state of affairs. (You do this now, and called the variables
distxanddisty.) In a PID controller, you keep a memory of past errors so that you can act differently based upon different perspectives of the error.You create a PID controller for each of the controllable states for the object you are trying to control (the enemy). So your update logic will change to:
You can now get a variety of behaviors out of enemies by varying the
p,i,dparameters of thePIDobject. To replicate your current AI, you would set:While a more interesting AI can be achieved by bumping up the
iparameter and reducingpeven further:Every so often you will want to clear the enemy’s memory if he lasts for a very long time. Just call
pidx.reset(distx)to reset that memory.Also you will still want to rate-limit the
velx, velyas given earlier in this answer.What are the benefits of all this complexity? You get enemies that behave very naturally as compared to simpler maths. I also wanted to point out that you’re moving along the right tracks with your
distx * 0.00005logic.(1) Think of controls engineers as those who study the behavior of closed systems and use that knowledge to force the system to act in ways they desire.