Log In  

Hi

Math isn't my strong side, so not sure if there is a simple solution to this or how to solve it really but I'm sure its a piece of cake for someone here.

If I'd want to limit the line drawn with this snippet of code to say 10px from 64,64:
function _draw()
cls()
h = stat(32);
v = stat(33);
line(64,64,h,v,10)
end

How would that math look?

P#94247 2021-06-30 18:28

1

Here's the code which should do what you want. I'll explain it down below in case you want to know why it works. And of course this assumes that you've enabled mouse support, otherwise h and v will just always be 0.

function _draw()
  cls()
  h = stat(32) - 64;
  v = stat(33) - 64;
  l = sqrt(h^2 + v^2)
  line(64,64,64+((h/l)*10),64+((v/l)*10),10)
end

Feel free to skip this:

So, I changed h and v to be the mouse coordinates minus 64 because we want to calculate the length of the line from the center of the screen to the mouse. So 'stat(32) - 64' gives the length of the line segment from the mouse-x to the center of the screen, and 'stat(33) - 64' does likewise for the mouse-y.
Edit: Not to the center of the screen but to the center line in the x and y direction respectively.

The value l is just calculated using the pythagorean theorem (a^2 + b^2 = c^2). So that gives us the length of the line from the center of the screen to the mouse.

If we divide h and v by l then we create a smaller triangle where the length in the direction of the mouse is just one. Then you can multiply by whatever final length you want, in this case 10, and you get the line segment you're looking for.

P#94248 2021-06-30 19:09 ( Edited 2021-06-30 19:11)

Thank you kind jasondelaat, for the code example and explanation. You describe it well and I understand it, but it will take some time for me to wrap my head around. I think this is the first time I've ever used square root in a practical way :)

Thanks again !

P#94250 2021-06-30 19:21
1

No worries, happy to help!
Pythagoras will come in handy any time you need to calculate the distance between objects in 2D space. So if you ever find yourself doing line-of-sight or path finding or anything like that it's worth keeping in mind.

P#94257 2021-06-30 20:19

I kind of figured it was important for distances as you say, and I will definitely keep this in mind for the future. Have been scribbling on some paper this evening from the formula/code, replicating it on a grid and calculating by hand to get a grasp on it. Math for me first becomes easy when it can be visualized, but I still quite don't know how to visualize this although the formula isnt hard. I'll get there in due time, I'm sure :)

Cheers !!

P#94269 2021-06-30 21:39

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 19:47:17 | 0.007s | Q:14