What is wrong with my conversion of X Y Z co-ordinates to screen X Y co-ordinates?

后端 未结 1 1758
南笙
南笙 2021-02-06 16:11

I am working on a HTML5 Canvas demo of spheres bouncing in 3D space. This is very simple to do. Each ball has X, Y, and Z co-ordinates. These co-ordinates are then converted int

相关标签:
1条回答
  • 2021-02-06 16:34

    Currently your origin (origo) is in the top left corner. To project x and y so that your origin, or here: the Cartesian coordinate [0, 0, 0] is in center of the screen:

    f = fieldOfView / (viewDistance + z);
    px = x * f + screenWidth * 0.5;
    py = y * f + screenHeight * 0.5;
    
    • fieldOfView is related to focal distance, use for example 128 - 256.
    • viewDistance translates z values.
    • px and py are the projected 2D coordinates.

    If all your coordinates are positive they will be drawn on the right/bottom side of the origin so you need to use negative values to have something on the left/top side of it.

    Additionally: you can replace the line operations with rect()s and if you cache them to an off-screen canvas you can "blit" that to main canvas instead of clearing and re-drawing each time which gives you a little better performance.

    0 讨论(0)
提交回复
热议问题