This is a question related to programming but it is mostly pure mathematics and that is why I am asking it here. Please don't tell me to move this to the Programming Stack Exchange. It is here for a reason; it has to do with trigonometry.
I'm building a game in the Lua programming language for fun (even if you don't know programming, you can probably help me with this as it applies to any mathematics). My problem is I have an x and y variable defined in a table for the player. A table for those of you who do not know programming is simply a set of values in an organized data structure:
player = {}
player.x = 10
player.y = 10
player.velocity = 50
My goal is to have the player move towards the mouses position on the screen. I have it currently set up to increase/decrease the x value and y value for every update depending on the mouse position. My code looks something like this:
function update(delta_time) -- delta_time is time in milliseconds since last update
# If statements use logic to make a decision.
# This if statement checks whether the mouse position is in Quadrant I.
if mouse.x > screen.width and mouse.y < screen.height then
player.x = player.x + player.velocity * delta_time # Increases x by 1
player.y = player.y + player.velocity * delta_time # Increases y by 1
end
That was just one example of a direction that I would define. My problem is that I don't want to have gigantic blocks of if statements checking for what quadrant the x and y position of the mouse are in, and adjusting the players x and y position accordingly. I would rather have a fluid 360 degree detection that can move the player towards the angle the mouse is positioned from the center. I was thinking I could use some trigonometric function to plug in the mouse position and output x and y variables for the increment of the players x/y position.
Another problem I have is when I move the player to the right of the screen, I will simply increase the x value, but when I move the player to the northeast side of the screen, I increase the x AND y value. This means that the player will go 2 TIMES faster depending on how fine the angle of movement is. When I make north east east angles and north west west, the player now goes 3 TIMES faster because I increase/decrease y by 2 and x by 1. I have no idea how to fix this. I am really good with math and trig, but I am bad at applying it to my game. All I need is someone to switch the lights on for me and I will understand. Thank you for your time if you actually read all this.
Just compute the two numbers
dx = mouse.x - player.xanddy = mouse.y - player.yand set
d = sqrt(dx^2 + dy^2).Then modify your instructions for moving the player like that:
Explanation: $(dx/d, dy/d)$ is the unit vector from the player to the mouse, so all you have to do is to multiply it by the appropriate length, to get the displacement vector.