www.jpct.net

jPCT - a 3d engine for Java => Support => Topic started by: rolz on February 28, 2006, 09:28:05 pm

Title: a point inside polygon
Post by: rolz on February 28, 2006, 09:28:05 pm
I've got stuck with a math question.

How to determine Z coordinate for a point inside a polygon with given x and y coordinates ?

Assume we have SimpleVector p1, p2, p3 - vertices of the polygon.
then we have float x, float y - coordinates of point inside this polygon. How do we find Z coordinate that belongs to this polygon ?

Spent 30 minutes trying to figure this out and finally gave up. ;) .. any suggestions ?
Title: a point inside polygon
Post by: EgonOlsen on February 28, 2006, 10:17:19 pm
Maybe like so...(but i'm not sure as i don't have a valid test case for this. I've just done this on paper and i can hardly read my own writings...:wink: ):

Code: [Select]
import com.threed.jpct.*;

public class TestPoint {
  public static void main(String[] args) {

    // The vertices
    SimpleVector p0=new SimpleVector(10,10,40);
    SimpleVector p1=new SimpleVector(0,10,20);
    SimpleVector p2=new SimpleVector(10,0,10);

    // The "target" vertex
    SimpleVector px=new SimpleVector(10,0,0);

    // The vectors from p0 to the other vertices
    SimpleVector a=p1.calcSub(p0);
    SimpleVector b=p2.calcSub(p0);

    float d=0.00000000001f;
    float div=(b.y*a.x-b.x*a.y);
    float div2=a.y;
    if (div==0) {
      div=d;
    }

    if (div2==0) {
      div2=d;
    }

    // Some linear algebra...could be just plain wrong...:-)
    float y=((-p0.y+px.y)*a.x+(p0.x-px.x)*a.y)/div;
    float x=(-p0.y+px.y-y*b.y)/div2;

    px.z=p0.z+x*a.z+y*b.z;

    System.out.println(px);
  }
}
Title: a point inside polygon
Post by: EgonOlsen on March 03, 2006, 05:56:47 pm
Have you tried it? Did it work?
Title: a point inside polygon
Post by: rolz on March 08, 2006, 03:43:32 pm
Sorry for late response. Nope, it didnt worked. Sometimes player flies over the ground, sometimes falls through.
Title: a point inside polygon
Post by: rolz on March 08, 2006, 04:27:08 pm
My bad, i was putting vertices in wrong order. It works now Thanks ! ;)