Finding points on a rectangle at a given angle

后端 未结 7 2025
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 02:43

I\'m trying to draw a gradient in a rectangle object, with a given angle (Theta), where the ends of the gradient are touching the perimeter of the rectangle.

7条回答
  •  醉话见心
    2020-12-14 03:19

    Unreal Engine 4 (UE4) C++ Version.

    Note: This is based off of Olie's Code. Based on Belisarius's Answer. Give those guys upvotes if this helps you.

    Changes: Uses UE4 syntax and functions, and Angle is negated.

    Header

    UFUNCTION(BlueprintCallable, meta = (DisplayName = "Project To Rectangle Edge (Radians)"), Category = "Math|Geometry")
    static void ProjectToRectangleEdgeRadians(FVector2D Extents, float Angle, FVector2D & EdgeLocation);
    

    Code

    void UFunctionLibrary::ProjectToRectangleEdgeRadians(FVector2D Extents, float Angle, FVector2D & EdgeLocation)
    {
        // Move theta to range -M_PI .. M_PI. Also negate the angle to work as expected.
        float theta = FMath::UnwindRadians(-Angle);
    
        // Ref: http://stackoverflow.com/questions/4061576/finding-points-on-a-rectangle-at-a-given-angle
        float a = Extents.X; // "a" in the diagram | Width
        float b = Extents.Y; // "b"                | Height
    
        // Find our region (diagram)
        float rectAtan = FMath::Atan2(b, a);
        float tanTheta = FMath::Tan(theta);
    
        int region;
        if ((theta > -rectAtan) && (theta <= rectAtan))
        {
            region = 1;
        }
        else if ((theta > rectAtan) && (theta <= (PI - rectAtan)))
        {
            region = 2;
        }
        else if ((theta > (PI - rectAtan)) || (theta <= -(PI - rectAtan)))
        {
            region = 3;
        }
        else
        {
            region = 4;
        }
    
        float xFactor = 1.f;
        float yFactor = 1.f;
    
        switch (region)
        {
            case 1: yFactor = -1; break;
            case 2: yFactor = -1; break;
            case 3: xFactor = -1; break;
            case 4: xFactor = -1; break;
        }
    
        EdgeLocation = FVector2D(0.f, 0.f); // This rese is nessesary, UE might re-use otherwise. 
    
        if (region == 1 || region == 3)
        {
            EdgeLocation.X += xFactor * (a / 2.f);              // "Z0"
            EdgeLocation.Y += yFactor * (a / 2.f) * tanTheta;
        }
        else // region 2 or 4
        {
            EdgeLocation.X += xFactor * (b / (2.f * tanTheta)); // "Z1"
            EdgeLocation.Y += yFactor * (b / 2.f);
        }
    }
    

提交回复
热议问题