2017-07-22 1 views
2

J'ai un code qui va détecter le début et la fin d'une action cliquer-glisser, et l'enregistrer à 2 points vector2. J'utilise ensuite ce code pour convertir:Convertir 2 vector2 points en un rectangle dans xna/monogame

public Rectangle toRect(Vector2 a, Vector2 b) 
{ 
    return new Rectangle((int)a.X, (int)a.Y, (int)(b.X - a.X), (int)(b.Y - a.Y)); 
} 

Le code ci-dessus ne fonctionne pas et googler, a produit jusqu'ici peu concluants. Quelqu'un peut-il s'il vous plaît me fournir un code ou une formule pour convertir correctement cela?
Remarque: un vecteur2 a un x et un y, et un rectangle a un x, un y, une largeur et une hauteur.

Toute aide est appréciée! Merci

Répondre

4

Je pense que vous devez avoir une logique supplémentaire pour décider quel vecteur utiliser en haut à gauche et lequel utiliser en bas à droite.

Essayez ceci:

public Rectangle toRect(Vector2 a, Vector2 b) 
    { 
     //we need to figure out the top left and bottom right coordinates 
     //we need to account for the fact that a and b could be any two opposite points of a rectangle, not always coming into this method as topleft and bottomright already. 
     int smallestX = (int)Math.Min(a.X, b.X); //Smallest X 
     int smallestY = (int)Math.Min(a.Y, b.Y); //Smallest Y 
     int largestX = (int)Math.Max(a.X, b.X); //Largest X 
     int largestY = (int)Math.Max(a.Y, b.Y); //Largest Y 

     //calc the width and height 
     int width = largestX - smallestX; 
     int height = largestY - smallestY; 

     //assuming Y is small at the top of screen 
     return new Rectangle(smallestX, smallestY, width, height); 
    } 
+0

Merci! le code fonctionne vraiment bien! –

+0

Vous cherchez le 'smallestY' et pourtant le code' int smallestY = (int) Math.Min (a.X, b.X); 'qui est incorrect – MickyD

+0

@MickyD Édité pour corriger l'erreur, merci de repérer celui-là! –