2
\$\begingroup\$

Please see attached screenshot.

enter image description here

Here's how it works.

A is a slider that goes up and down, and the red line uses the centre point of the A slider to draw its start point.

B is another slider, but this goes left and right (stops in the middle as shown below).

The current issue is, the red line should always rest on top of B like a see-saw. Currently the line's end point has a fixed x position so it is always in line with the green crosses below to the right. But I need to position the end Y point of the line correctly so that the line as a whole is resting on top of B at all times. Whether the user slides A or B.

My guess is I need to work out some form of distance calculation with angles. I have something along the lines of:

Called 60fps:

this.startPoint.x = this.verticalSliderModel.xPos;
this.startPoint.y = this.verticalSliderModel.yPos;
this.endPoint.x = 653;
this.endPoint.y = this.horizontalSliderModel.yPos;

var angle = Phaser.Math.angleBetween(this.startPoint.x, this.startPoint.y, this.endPoint.x, this.endPoint.y);

this.seeSawController.updateModel(this.startPoint, this.endPoint, angle, width);
this.seeSawController.updateView();

I then use html canvas to draw the line:

update(start:Point, end:Point, angle:number, width:number) {

    this.bmd.clear();
    this.bmd.ctx.beginPath();
    this.bmd.ctx.moveTo(start.x, start.y);
    this.bmd.ctx.lineTo(end.x, end.y);
    this.bmd.ctx.lineWidth = 4;
    this.bmd.ctx.stroke();
    this.bmd.ctx.closePath();
    this.bmd.render();
}

So yeah I want to calculate the green cross plot points moving forward.

\$\endgroup\$
5
\$\begingroup\$

You can solve this with some basic trigonometry.

I wrote the code in Unity, but the general idea should be the same.

Consider the following image:

enter image description here

We already have P1 and P2.
Here is some code to calculate the rest with comments:

    //Get points P1 and P2 based on circles
    Vector2 p1 = A.transform.position;
    Vector2 p2 = B.transform.position + new Vector3 (0, B.Radius);

    //calculate P3 using defined area bounds
    float px = AreaRight.transform.position.x + AreaRight.transform.localScale.x;
    Vector2 p3 = new Vector2 (px, p1.y);

    //Calculate angle (a) between P1 and P2
    float angle = Mathf.Atan2 (p2.y - p1.y, p2.x - p1.x);

    //Caculate the distance (h) between P3 and P4
    float height = Mathf.Tan (angle) * (p3 - p1).magnitude;

    //Set the P4 point we are looking for
    Vector2 p4 = new Vector2 (p3.x, p3.y + height);

    //Draw the line
    Line.SetLine (A.transform.position, p4);

Bonus gif of demo:

enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.