Setting the pitch and yaw of a mob relative to a target

Discussion in 'Plugin Development' started by Jnorr44, Apr 26, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    Jnorr44

    I need to make it so a mob looks at a target. I know this can be done via the setPitch and setYaw methods, but first I need the pitch and yaw to set. I only have a target and a current location available.

    I have tried this so far: (found is current, target is obviously the target)

    Code:
                float pitch = 0, yaw = 0;
                double a = target.getZ() - found.getZ();
                double b = target.getX() - found.getX();
                double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
                double d = target.getY() - found.getY();
                double e = Math.sqrt(Math.pow(c, 2) + Math.pow(d, 2));
                yaw = (float) Math.toDegrees(Math.asin(a / c));
                pitch = (float) Math.toDegrees(Math.asin(d / e));
    Does anyone know some math equation to solve this?
     
  2. Offline

    Tzeentchful

    Jnorr44
    Here is a method I use. I originally got it from bergkiller.
    Code:java
    1.  
    2. public static Location lookAt(Location loc, Location lookat) {
    3. //Clone the loc to prevent applied changes to the input loc
    4. loc = loc.clone();
    5.  
    6. // Values of change in distance (make it relative)
    7. double dx = lookat.getX() - loc.getX();
    8. double dy = lookat.getY() - loc.getY();
    9. double dz = lookat.getZ() - loc.getZ();
    10.  
    11. // Set yaw
    12. if (dx != 0) {
    13. // Set yaw start value based on dx
    14. if (dx < 0) {
    15. loc.setYaw((float) (1.5 * Math.PI));
    16. } else {
    17. loc.setYaw((float) (0.5 * Math.PI));
    18. }
    19. loc.setYaw((float) loc.getYaw() - (float) Math.atan(dz / dx));
    20. } else if (dz < 0) {
    21. loc.setYaw((float) Math.PI);
    22. }
    23.  
    24. // Get the distance from dx/dz
    25. double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2));
    26.  
    27. // Set pitch
    28. loc.setPitch((float) -Math.atan(dy / dxz));
    29.  
    30. // Set values, convert to degrees (invert the yaw since Bukkit uses a different yaw dimension format)
    31. loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI);
    32. loc.setPitch(loc.getPitch() * 180f / (float) Math.PI);
    33.  
    34. return loc;
    35. }
    36.  
     
  3. Offline

    Jnorr44

    Tzeentchful
    I tried that but for some reason they have not been looking at the target.
     
Thread Status:
Not open for further replies.

Share This Page