Calculate a vector from the center of a square to edge based on radius

前端 未结 5 1877
Happy的楠姐
Happy的楠姐 2021-01-06 12:58

Given a square (described by x, y, width, height) and an angle (in radians) I need to calculate a vector that originates at the squares centre and terminates at the point th

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 13:51

    Edit: There is another working implementation from Pavel now (good dedication from him to put in effort debugging his solution) but I'll leave this here as another alternative that works only for squares (Pavel's works for Rectangles).

    private function calculatePointOnSquare(width:Number, angle:Number):Point
    {
        // simple angle wrapping             
        angle = (Math.PI*2 + angle) % (Math.PI*2);
    
        // calculate a normalized vector from the centre
        // of a square to the edge taking into account
        // the eight possible quadrants
        var myX:Number;
        var myY:Number;
        if(angle < Math.PI/4)
        {
            myX = 1;
            myY = Math.tan(angle);
        }
        else if(angle < Math.PI/2)
        {
            myX = Math.tan(Math.PI/2 - angle);
            myY = 1;
        }
        else if(angle < 3*Math.PI/4)
        {
            myX = -Math.tan(angle - Math.PI/2);
            myY = 1;
        }
        else if(angle < Math.PI)
        {
            myX = -1;
            myY = Math.tan(Math.PI - angle);
        }
        else if(angle < 5*Math.PI/4)
        {
            myX = -1;
            myY = -Math.tan(angle - Math.PI);
        }
        else if(angle < 3*Math.PI/2)
        {
            myX = -Math.tan((3*Math.PI/2) - angle);
            myY = -1;
        }
        else if(angle < 7*Math.PI/4)
        {
            myX = Math.tan(angle - (3*Math.PI/2));
            myY = -1;
        }
        else
        {
            myX = 1;
            myY = -Math.tan(Math.PI*2 - angle);
        }
    
        // scale and translate the vector
        return new Point(
            (myX * width/2) + width/2, 
            (myY * width/2) + width/2);
    }
    

提交回复
热议问题