2012-12-25 3 views
1

Im struggeling pour mettre en œuvre une fonction qui me dit au fond, si un rayon « se rapproche assez » pour un objetComment calculer Rayintersection 3D pour la cueillette

Fondamentalement, je mis en œuvre Implementing Ray Picking @nornagon soloution pour créer le Ray. Mon objet sur l'écran est centré autour d'un point. Je suppose que si le Ray est à une certaine distance de ce point, l'objet est sélectionné.

J'appelle ces 3 points (X, Y, Z): _pickFrom, _pickTo et pO

Pour commencer, voici ma méthode pour calculer le rayon en fonction de MousePosition à l'écran:

public static void Pick(int x, int y) 
    { 
     float nx = 2.0f * ((float)x)/((float)_width) - 1.0f; 

     float ny = 1.0f - 2.0f * ((float)y)/((float)_height); 

     Matrix4 unview = Matrix4.Invert(Matrix4.Mult(_projectionMatrix, _modelviewMatrix)); 

     Vector4 nearPoint = Vector4.Transform(new Vector4(nx, ny, 0, 1), unview); 

     _pickTo = nearPoint - _pickFrom; 
    } 

_pickFrom est la position de la caméra dans la scène. _pickTo est la direction de la pioche. _width et _height sont les tailles de rendu. Comment puis-je maintenant implémenter une fonction qui me donne la distance d'un point à la piqure?

Répondre

2

Je pensais que ce moi-même maintenant:

public void SetMouse(int x, int y) 
{ 
    float xpos = 2.0f * ((float)x/(float)_width) - 1.0f; 
    float ypos = 2.0f* (1.0f - (float)y/(float)_height) - 1.0f; 

    Vector4 startRay = new Vector4(xpos, ypos, -1, 1); 
    Vector4 endRay = new Vector4(xpos, ypos, 1, 1); 


    Matrix4 trans = _modelView.Data * _projection.Data; 
    trans.Invert(); 
    startRay = Vector4.Transform(startRay, trans); 
    endRay = Vector4.Transform(endRay, trans); 

    _pickFrom = startRay.Xyz/startRay.W; 
    _pickTo = endRay.Xyz/endRay.W; 
} 

....

public float Distance(Vector3 p) 
{ 
    Vector3 x1 = _pickFrom; 
    Vector3 x2 = _pickTo; 

    return Vector3.Cross 
    (Vector3.Subtract(p, x1), 
    Vector3.Subtract(p, x2) 
    ).Length/Vector3.Subtract(x2, x1).Length; 
} 
Questions connexes