Discuss Scratch

bsteichman
Scratcher
500+ posts

help with Z clipping

does anyone have a better algorithm for finding the Z of a given pixel based on the 3 points of the triangle? here is my current code, and it works okish


but the problem is that it doesn't do its job perfectly, let me show you what I mean:
These are my 2 triangles, at first glance, you notice they look perfectly fine all clipping together in harmony, but then you realize that clipping faces shouldn't have a curved intersection.
this is what it should look like
this just has to do with my algorithm using distances, so I would appreciate it if anyone has a better algo for getting the z that would be great
PutneyCat
Scratcher
500+ posts

help with Z clipping

May be better ways and I haven't tested this but FWIW these are the lines I'd be thinking along. The basic idea is to express the point as a combination of the AB and AC vectors, applying to each a number between 0 and 1. Once you have those two numbers, z is easy to work out.
Here is a simple worked example. Suppose your triangle is:
A = (1,1,0)
B = (3,3,2)
C = (3,1,0)
P = (3,2, z?)
Get the vectors by subtracting end point from start point.
AB vector = (2,2,2)
AC vector = (2,0,0)
We also want P relative to A, again just subtracting.
P (relative to A) = (2,1, ?)
Now we can ignore z values for a bit, and consider just x, y.
What we want is m(2,2) + n(2,0) = 2,1
That is a simple pair of simultaneous equations, i.e.
2m + 2n = 2
2m + 0n = 1
You can search for simultaneous equations on Scratch to find simple projects that will solve this kind of equation, for example this one seemed to work on a quick look, with only a couple of lines of code required.
In the example, it's easy to see that m=0.5 and n= 0.5.
Then just apply those numbers to the respective z components of the AB and AC vectors: 0.5 * 2 + 0.5 * 0 = 1.
So the z value of P is 1.

Last edited by PutneyCat (Oct. 7, 2024 10:21:35)

Powered by DjangoBB