Normalize Diagonal movement

Hi guys,

How do I normalize the diagonal movement of my Player?

I am using the physics extension & applying forces to move the player.

Cheers A

You can use two variables storing the movement X and Y, normalize the variables if there is a diagonal movement and then apply forces:

[code]Conditions: No conditions (always)
Actions: Do = 0 to variable MoveX
Do = 0 to variable MoveY

Conditions: Left key is pressed
Actions: Do - 1 to variable MoveX

Conditions: Right key is pressed
Actions: Do + 1 to variable MoveX

Conditions: Up key is pressed
Actions: Do - 1 to variable MoveY

Conditions: Down key is pressed
Actions: Do + 1 to variable MoveY

Conditions: Variable MoveX != 0
Variable MoveY != 0
Actions: Do / sqrt(2) to variable MoveX
Do / sqrt(2) to variable MoveY

Conditions: No conditions (always)
Actions: Add a force to Player with magnitude X=5Variable(MoveX) ; Y=5Variable(MoveY)[/code]

Cheers I will give it a go!

Hi Lizard,

I have mashed (i think that is the appropriate word to describe ) what you mentioned in your previous post with the code I have. now I have a feeling I have done mine wrong and would appreciate a boot in the correct direction. Do I need to add the bits of code down the bottom as well?

I’m thinking on this:


The idea is to first get the movement keys pressed, so you know if there is a diagonal movement before adding the force. You can’t normalize a force already applied, you could add a counterforce, though :neutral_face:
The factor “100” used when adding the forces is the total speed, the movement vector (MoveX; MoveY) is normalized so you can multiply this vector by a factor X to get a vector of length (speed) X :slight_smile:

Hi Lizard-13,

Cheers. That makes more sense, I’ll run through that and report back.

Once again I really really appreciate all your assistance with my silly questions :slight_smile:.

Cheers A

Hi Lizard,

This is what my code looks like now. It appears to work. Much simpler than what I had previously. With regards to the speed of movement, I can increase that by upping pixels moved? from 100 to whatever is required?

Exactly, right now the object is moving at 100 pixels/second :slight_smile:

Cheers Lizard-13!

The only other question I had was around the variables. Should the be created as Scene, (that’s what I have currently set) or Global?

Depends on the variable use, set MoveX and MoveY as global variables has no sense, they store no important information to save from one scene to another.
Global variables should be used when you need to save data through scenes, as game options, total game score, etc.

Hi Lizard-13,

Thanks for helping clarify :slight_smile:.