# Finding the correct X and Y speed of object using the slope between two points

This topic is 2537 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey everyone, in my 2d platformer I'd like the player to be able to use a jet pack to get around. When the space bar is pressed the player will move toward the mouse, so the two points from which the slope is calculated are the player location and the mouse location. Because it's a 2d game I need to calculate the X and Y speeds to move diagonally given a set movement speed. Below is my current implementation for this:

 var_SlopeX = var_Mouse_3DPositionX - var_Character_PositionX var_SlopeZ = var_Mouse_3DPositionZ - var_Character_PositionZ var_Slope_TotalUnits = ABS(var_SlopeX) + ABS(var_SlopeZ) var_Slope_SingleUnit = var_Character_MovementSpeed / var_Slope_TotalUnits var_Character_SpeedX = var_SlopeX * var_Slope_SingleUnit var_Character_SpeedZ = var_SlopeZ * var_Slope_SingleUnit 

To clarify the code a bit, what I'm doing is finding the X and Z slope and then using it to find the total units between the player's location and the mouse's location. I then calculate how much a single unit of movement is so it can be used to find the X and Z speed. This is working fairly well except that when the mouse is either directly above, below, left or right of the character it appears to be moving faster than if it's diagonal of the character's location.

This *might* just be my brain playing tricks on me, but I'm fairly confident that's not the case. What changes, if any, would need to be made to ensure that the player is moving at an equal speed no matter where the mouse is located?

##### Share on other sites
The magnitude of the hypotenuse of a triangle with sides X and Y is sqrt(X*X + Y*Y).

##### Share on other sites
Change this:
var_Slope_TotalUnits = ABS(var_SlopeX) + ABS(var_SlopeZ)

to this:
var_Slope_TotalUnits = SQRT(var_SlopeX*var_SlopeX + var_SlopeZ*var_SlopeZ)

Your naming convention is highly non standard. What you call "slope" is a "vector". What you call "total units" is called "length". And "speed" refers to a single real number, but the vector quantity is called "velocity".

##### Share on other sites
Wow, thanks for the quick replies; worked like a charm! Sorry about the naming convention. I guess I just chose names that made sense to me since it's just me working on the project. Probably good practice to use the standard versions.

1. 1
Rutin
67
2. 2
3. 3
4. 4
5. 5

• 11
• 11
• 21
• 10
• 33
• ### Forum Statistics

• Total Topics
633438
• Total Posts
3011882
• ### Who's Online (See full list)

There are no registered users currently online

×