Moving a square from a starting point to the position of a mouse click at a fixed speed

前端 未结 2 1893
刺人心
刺人心 2020-12-11 21:58

I\'m trying to move a square from it\'s original position to the coordinates of my mouse when I click. The code I have somewhat works, but the square does not go directly to

2条回答
  •  生来不讨喜
    2020-12-11 22:34

    Using the pythagorian theorem we can calculate the distance D ie sqrt((targetx-startx)^2+(target-starty)^2).

    Using your velocity variable (ill call it V)we can calculate a time variable T as D/V ie distance over velocity.

    We can then get the separate x and y velocity as xdistance/T and ydistance/T or (targetx-startx)/T and (targety-startat)/T (Note that an exception for if T == 0 must be implementerad to avoid errors)

    Using time fragments to calculate the x and y velocity so that the total velocity remains the same is computationally unnecessary with the only upside being that we avoid dividing by zero but then again that is easily fixable with a single if statement(if(T != 0.0)).

    Using this or similar methods will make your program run faster as less computations are needed. The time save is too small to be noticeable with modern computers but it keeps the code cleaner. Good luck with your project.

提交回复
热议问题