I am building a program in javascript that renders a 3d world onto the 2d screen from scratch. I created a function to calculate the x value on the screen that a 3d point will be displayed at. It also needs to factor in the angle of the horizontal that the points need to be rotated around. To do this I tried converting to spherical coordinates and then adding the viewer's x angle onto one of the values. For some reason it distorts everything when you aren't looking at zero degrees. Here is the code and here is the output of the whole program:https://3d.napoleon1027.repl.co/ (Right now it is set to slowly rotate every three seconds, and you can move with the arrow keys/WSAD)
function fx(x,y,z){
//calculates the x, y, and z values relative to your position
z-=pz
x-=px
y-=py
//converts the cartesian coordinates to spherical
var r=Math.sqrt(x**2+y**2+z**2)
var t=Math.acos(z/r)
var f=Math.atan(y/x)
if(x<0){
f+=Math.PI
}
//adds your angle to the angle of theta
t+=xangle
//converts the spherical coordinates back to cartesian
x=r*Math.cos(f)*Math.sin(t)
y=r*Math.sin(f)*Math.sin(t)
z=r*Math.cos(t)
//adds the player coordinates back
z+=pz
x+=px
y+=py
//returns the x value that this point should be drawn onto the screen at
return (x-px)/(z-pz);
}