Advertisement
otorp2

move hypoten

Apr 9th, 2016
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. Create a vector in the direction that you want the enemy to move. That's easy:
  2.  
  3. dir.x = player.x - enemy.x;
  4. dir.y = player.y - enemy.y;
  5. Now normalize this vector. That means divide the terms by the magnitude (the hypotenuse) of the vector.
  6.  
  7. hyp = sqrt(dir.x*dir.x + dir.y*dir.y);
  8. dir.x /= hyp;
  9. dir.y /= hyp;
  10. Now you just need to add that vector to the enemy's position, multiplied by the speed you want the enemy to move:
  11.  
  12. enemy.x += dir.x*speed;
  13. enemy.y += dir.y*speed;
  14. Here's how it works - if you add that initial vector to the enemy's position it will instantly be transported to the player. You obviously want to enemy to move at a slower speed. When you normalize the vector, you make it's magnitude (essentially the hypotenuse of the triangle it forms) equal to 1. So now, adding the direction vector moves the enemy by one unit. Multiply that 1 unit by the enemy's speed, and now it's moving at the correct speed.
  15.  
  16. Edit: all of this extends to 3D as well. You just need a z-component.
  17.  
  18. Further edits to comment on your code:
  19.  
  20. You are doing a lot of extra work. You have enough information once you calculate the hypotenuse to move the enemy towards the player. You don't need to use any trig at all - see my code above. You are also calculating (sort of) the magnitude twice:
  21.  
  22. float hypotenuse = sqrt((xDistance * xDistance) + (yDistance * yDistance));
  23. ...
  24. (playerX - enemyX)*(playerX - enemyX)+(playerY - enemyY)*(playerY - enemyY)
  25. The second time it's the distance squared which is a nice optimization, but unnecessary here because you've already calculated the distance and the distance squared.
  26.  
  27. Here's what I would do:
  28.  
  29. float xDistance = playerX-enemyX;
  30. float yDistance = playerY-enemyY;
  31. float hypotenuse = sqrt((xDistance * xDistance) + (yDistance * yDistance));
  32.  
  33. if(hypotenuse < 400){
  34.  
  35. YPos += timeFactor*200*(yDistance/hypotenuse);
  36. XPos += timeFactor*200*(xDistance/hypotenuse);
  37. }
  38. You'll notice that by removing the abs() I've also managed to remove the if(playerY > enemyY), etc parts.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement