Limit drag to an arc / radius of a given length

So I have a line drawn with graphics(). It’s anchored at one end, and the other end is draggable. I made a quick demo here, and so far, so good:

Dragging the marker around and redrawing the line is no problem, but what I’d like is for that line to have a maximum length of 100, so even if you’re still dragging beyond that point, the line would still follow the mouse, but not get any longer than 100. Dragging inside that maximum radius, the line would shrink as normal.

I’ve put together a visual that hopefully explains it:
drag-limit-explanation

The issue is that I suspect this is VERY MATHS and I am very, very weak with maths. Could anyone explain like I’m five what I need to do to my code to achieve this? Thank you!

2 Likes

Since your question seems the same as on StackOverflow the answer should be the same. So did you check this answer.

Basically:

  1. create a real Phaser.Math.Vector2
  2. use setLength of the vector, if the length is too long
  3. update the point / line coordinates

The StackOverflow answer has also a runable demo, I didn’t want to create a extra codepen, I hope that’s not problem.

You won’t need math since Phaser has helpe-functions, that will do the complicated math for you.

Phaser.Math.Vector2#limit() will do this also.

There’s also a funny way to do this with Phaser.Geom.Line:

// curve is Phaser.Geom.Line
var length = Phaser.Geom.Line.Length(curve);

if (length > 100) {
  Phaser.Geom.Line.Extend(curve, 0, 100 - length);
}

That was my question! And I’m guessing your answer? It’s absolutely what I was looking for, so thank you!

Yes, you are right, it was my answer. :slight_smile: I check StackOverflow the phaser discourse for interessting question, which I might be able to answer, if I have some freetime.

Thanks for these, Samme. I had a quick go with limit() (setting it at the point of creation) but it didn’t seem to do anything. But @akumagamo 's answer on SO answered it perfectly. I’ve updated my pen with their code for anyone else who’s looking for this solution:

let vector = new Phaser.Math.Vector2(
  pointer.x - point0.x,
  pointer.y - point0.y
).limit(maxLength);