I'm trying to move enemy towards player, while enemy also tries to avoid an obstacle if it's in its path. Here's a simple illustration of what I want to do:
What I've tried:
Making circular collision around the obstacle. It works but that makes the enemy impossible to hit.
I think going with an A* pathfinding algorithm might be a bit overkill especially since it's designed for multiple obstacles, where in my case there is only the mouse and wall collision concerned.
Moving the enemy towards the player, while also moving away from the obstacle at a slower speed. This works better because you can actually hit the enemy, but also slows down enemy if obstacle if it's in its path.
My questions:
Is there a better way to go about doing this?
Anything you would've done differently with my code to either improve or optimize?
Here's the code I have currently in my game logic and a fully-working example on jsFiddle.
// Calculate vector between player and target
var toPlayerX = playerPosX - enemyPosX;
var toPlayerY = playerPosY - enemyPosY;
// Calculate vector between mouse and target
var toMouseX = mousePosX - enemyPosX;
var toMouseY = mousePosY - enemyPosY;
// Calculate distance between player and enemy, mouse and enemy
var toPlayerLength = Math.sqrt(toPlayerX * toPlayerX + toPlayerY * toPlayerY);
var toMouseLength = Math.sqrt(toMouseX * toMouseX + toMouseY * toMouseY);
// Normalize vector player
toPlayerX = toPlayerX / toPlayerLength;
toPlayerY = toPlayerY / toPlayerLength;
// Normalize vector mouse
toMouseX = toMouseX / toMouseLength;
toMouseY = toMouseY / toMouseLength;
// Move enemy torwards player
enemyPosX += toPlayerX * speed;
enemyPosY += toPlayerY * speed;
// Move enemy away from obstacle (a bit slower than towards player)
enemyPosX -= toMouseX * (speed * 0.4);
enemyPosY -= toMouseY * (speed * 0.4);