Ok, so I found this Freebasic code somewhere and its close..
' http://www.dreamincode.net/forums/topic/239174-3d-perspective-projection/
' translated to FreeBasic
'' ----------------------------------------
'' Formula to solve Sx
'' ----------------------------------------
'' Ez = distance from eye to the center of the screen
'' Ex = X coordinate of the eye
'' Px = X coordinate of the 3D point
'' Pz = Z coordinate of the 3D point
''
'' Ez*(Px-Ex)
'' Sx = ----------------------- + Ex
'' Ez+Pz
'' ----------------------------------------
'' Formula to solve Sy
'' ----------------------------------------
'' Ez = distance from eye to the center of the screen
'' Ey = Y coordinate of the eye
'' Py = Y coordinate of the 3D point
'' Pz = Z coordinate of the 3D point
''
'' Ez*(Py-Ey)
'' Sy = ------------------- + Ey
'' Ez+Pz
type Vector2i
as integer x, y
end type
type Vector3i
as integer x, y, z
end type
sub main()
'' lets assume 640x480 res.
'' Our "eye" is where we are viewing from, which
'' is about 800 pixels towards me and in the center of
'' the screen.
dim as Vector3i eye = Type(320, 240, 800)
'' This is the point that we're projecting onto
'' our 2D plane.
dim as Vector3i P = Type(600, 200, 1000)
'' This will be the 2D coords of our perspective projection.
dim as Vector2i S
'' ----------------------------------------
'' Formula to solve Sx
'' ----------------------------------------
'' Ez = distance from eye to the center of the screen
'' Ex = X coordinate of the eye
'' Px = X coordinate of the 3D point
'' Pz = Z coordinate of the 3D point
''
'' Ez*(Px-Ex)
'' Sx = ----------------------- + Ex
'' Ez+Pz
S.x = (eye.z * (P.x-eye.x)) / (eye.z + P.z) + eye.x
'' ----------------------------------------
'' Formula to solve Sy
'' ----------------------------------------
'' Ez = distance from eye to the center of the screen
'' Ey = Y coordinate of the eye
'' Py = Y coordinate of the 3D point
'' Pz = Z coordinate of the 3D point
''
'' Ez*(Py-Ey)
'' Sy = ------------------- + Ey
'' Ez+Pz
S.y = (eye.z * (P.y-eye.y)) / (eye.z + P.z) + eye.y
print "Result of projection."
print "x: "; S.x
print "y: "; S.y
end sub
What I'm not sure of is the defined Z distance of the eye (cam) = 800 and the object's distance = 1000.. Is this relative to world center 0,0,0??
|