Skip to content
Advertisement

Limit dragged line to an arc / radius of a given length

I’m currently using Phaser 3, although my question isn’t technically restricted to that framework, as it’s more of a general JS/canvas/maths question, but:

I have a line drawn with graphics(). It’s anchored at one end, and the other end is draggable. I made a quick demo and so far, so good – you can see what I have already on CodePen.

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: Image showing the line being dragged, with a limiting arc where the drawing of the line stops, but the mouse can carry on.

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?

Edit: Adding code in a snippet here, as requested:

JavaScript
JavaScript

Advertisement

Answer

You are right, you would need some math, but phaser has many helper functions, that will do the heavy lifting.

The main idea is, of this solution is

  1. define a maxLength
  2. get the the new point on drag, and create a real Phaser Vector2
    • here is some math is needed, to create the vector, just calculate destination point minus origin point
      new Phaser.Math.Vector2(pointer.x - point0.x, pointer.y - point0.y) (origin point being the starting point of the desired vector, and destination point being the mouse pointer)
  3. calculate the length of the created vector and compare it with the maxLength
    • if too long adjust the vector, with the handy function setLength (link to the documentation, this is where you would have needed math, but thankfully Phaser does it for us)
  4. set the new coordinates for point1 and the curve endpoint

Here a quick demo (based on your code):

JavaScript
JavaScript

Optional – Code Version using Phaser.GameObjects.Line:

This uses less code, and thanks to the Line GameObject (link to Documentation), you can directly use the vector to update the line, and also don’t need the update function, graphics and so.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement