Reputation: 322
im trying to make the player look at at specific point. What i have looks at the point but only if its in its field of vision. and i would like for it to look up and down as well
public static void lookAt(double x, double y, double z) {
double l;
double w;
double c;
l = x - playerX;
w = z - playerZ;
c = Math.sqrt(l * l + w + w);
double alpha1 = -Math.asin(l / c) / Math.PI * 180;
double alpha2 = Math.acos(w / c) / Math.PI * 180;
if (alpha2 > 180) {
playerYaw = 180 - (float) alpha1;
} else {
playerYaw = (float) alpha1;
}
}
i looked for a pitch algorithm but none seem to work.
Upvotes: 0
Views: 2866
Reputation: 151
Late answer but oh well, you can calculate the pitch and yaw with simple trigonometry if you can get a unit vector that represents the direction from your position to the point you want to look at.
To start you need to subtract the your position by the point and normalize the result, that will give us the directional vector(unit vector) that we need.
Now we can calculate the angles, the arc sine of Y will give us the the pitch angle, and the arc tan of X and Z will give us the yaw angle.
To understand why: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
and now you should have the pitch and yaw, don't forget to convert them to degrees!
here's some code:
public static void LookAt(double px, double py, double pz , EntityPlayer me)
{
double dirx = me.getPosition(0f).X - px;
double diry = me.getPosition(0f).Y - py;
double dirz = me.getPosition(0f).Z - pz;
double len = Math.sqrt(dirx*dirx + diry*diry + dirz*dirz);
dirx /= len
diry /= len;
dirz /= len;
double pitch = Math.asin(dir.y);
double yaw = Math.atan2(dir.z, dir.x);
//to degree
pitch = pitch * 180.0 / Math.PI;
yaw = yaw * 180.0 / Math.PI;
yaw += 90f;
me.rotationPitch = (float)pitch;
me.rotationYaw = (float)yaw;
}
Upvotes: 3