I am trying to create a game using HTML5 Canvas and Javascript and I am unable to figure out how to (correctly) make the character move diagonally after clicking the canvas with the mouse. I did manage to make the character move diagonally, but I can’t set a speed so that regardless of the distance, it will move at the same speed… the further away you click, the faster it moves and the closer you click, the slower it moves. I want the speed to be the same regardless of where you click.
Here is what I have so far: http://pastebin.com/hUJBiQHq
How can I move the character diagonally on the canvas?
I actually went ahead and made quite a few changes. Ill try and go over each one.
The first thing I did was remove a lot of the
setTimoutcalls. You don’t really need a seperate one for movement and rendering. I also made it stop checking if the game was loaded after its actually loaded. Now once the game is loaded it will begin rendering.You also had your
onclickevent inside of the timeout which wasn’t needed. I moved it outside. A better approach and a subject for future reading would be usingaddEventListenerexplained nicely hereAnother thing I added right at the top is a shim for
requestAnimationFrameit is much better to use this oversetTimeoutand if you notice if it runs on a browser that doesn’t support animation frame it will fallback on a timeout. There are many benefits to using it explained here.Now onto the issue at hand!
txandtyare target x, and target y. They are the mouse coords subtracted from the player coords. You then can use these to perform a distance check like so,Next I check if the distance is greater than the speed, if it is we need to move closer to our position.
The next part calculates the velocity needed. We take the target x, and target y, and divide those by the distance which will give use the amount of pixels we need to travel to get to the target essentially. We then multiply this number by speed which gives us distance to move per tick. You then add these velocities to the players position to move the player (better explanation needed.. im terrible at explaining any math concepts :?)
Live Demo of it all working
Full Code