3
votes

I'm working on creating a simple 3D rendering engine in Java. I've messed about and found a few different ways of doing perspective projection, but the only one I got partly working had weird stretching effects the further away from the centre of the screen the object was moved, making it look very unrealistic. Basically, I want a method (however simple or complicated it needs to be) that takes a 3D point to be projected and the 3D point and rotation (possibly?) of the 'camera' as arguments, and returns the position on the screen that that point should drawn at. I don't care how long/short/simple/complicated this method is. I just want it to generate the same kind of perspective you see in a modern 3D first person shooters or any other game, and I know I may have to use matrix multiplication for this. I don't really want to use OpenGL or any other libraries because I'd quite like to do this as a learning exercise and roll my own, if it's possible.

Any help would be appreciated quite a lot :) Thanks, again - James

Update: To show what I mean by the 'stretching effects' here are some screen shots of a demo I've put together. Here a cube (40x40x10) centered at the coords (-20,-20,-5) is drawn with the only projection method I've got working at all (code below). The three screens show the camera at (0, 0, 50) in the first screenshot then moved in the X dimension to show the effect in the other two.

Camera at (0,0,50)Camera moved a bit in the X coordCamera moved even further

Projection code I'm using:

public static Point projectPointC(Vector3 point, Vector3 camera) {
    Vector3 a = point;
    Vector3 c = camera;
    Point b = new Point();

    b.x = (int) Math.round((a.x * c.z - c.x * a.z) / (c.z - a.z));
    b.y = (int) Math.round((a.y * c.z - c.y * a.z) / (c.z - a.z));

    return b;
}
1

1 Answers

1
votes

You really can't do this without getting stuck in to the maths. There are loads of resources on the web that explain matrix multiplication, homogeneous coordinates, perspective projections etc. It's a big topic and there's no point repeating any of the required calculations here.

Here is a possible starting point for your learning:

http://en.wikipedia.org/wiki/Transformation_matrix

It's almost impossible to say what's wrong with your current approach - but one possibility based on your explanation that it looks odd as the object moves away from the centre is that your field of view is too wide. This results in a kind of fish-eye lens distortion where too much of the world view is squashed in to the edge of the screen.