beek
beek

Reputation: 3746

Three.js calculate position at edge of rectangle when I know the angle from center

I'm trying to calculate position 2 in the illustration below.

I know position 1 from

  this._end = new THREE.Vector3()
  this._end.copy( this._rectanglePos )
     .sub( this._circlePos ).setLength( 1.1 ).add( this._circlePos )

Where the radius of the circle is 2.2

illustration of problem

I'm now trying to work out a position on the edge of the rectangle along this intersect.

I've found an equation written in pseudo code which I turned into this function

 function positionAtEdge(phi, width, height){
   let c = Math.cos(phi)
   let s = Math.sin(phi)
   let x = width/2
   let y = height/2

    if (width * Math.abs(s) < height * Math.abs(c)){
        x -= Math.sign(c) * width / 2
        y -= Math.tan(phi) * x
    } 
    else{
        y -= Math.sign(s) * height / 2
        x -= cot(phi) * y
    }

    return {x, y, z: 0}

    function cot(aValue){
        return 1/Math.tan(aValue);
    }
}

And this kind of works for the top of the rectangle but starts throwing crazy values after 90 degrees. Math didn't have a coTan function so I assumed from a little googling they meant this cot function.

Anyone know an easier way of finding this position 2 or how to convert this function into something useable.

Upvotes: 1

Views: 314

Answers (2)

ScieCode
ScieCode

Reputation: 1735

This is a general purpose solution, which is independent of their relative position.

Live Example (JSFiddle)

function getIntersection( circle, rectangle, width, height ) {

    // offset is a utility Vector3.
    // initialized outside the function scope.
    offset.copy( circle ).sub( rectangle );

    let ratio = Math.min( 
        width * 0.5 / Math.abs( offset.x ),
        height * 0.5 / Math.abs( offset.y )
    );

    offset.multiplyScalar( ratio ).add( rectangle );

    return offset;

}

Upvotes: 3

manthrax
manthrax

Reputation: 5036

You don't need any transcendental functions for this.

Vsb = (Spherecenter - rectanglecenter)

P2 = rectanglecenter + ((vsb * rectangleheight * .5) / vsb.y)

Upvotes: 0

Related Questions