Moving Our Player with "sqrMagnitude"


Early in the process of developing CoA we noticed a slight issue with the way the player travels. For starters, the player moved rather quickly. Additionally, somebody pointed out that holding down the vertical and horizontal movement keys for the player character caused them to move considerably faster than initially intended. I wasn't certain when this would be resolved and was not tasked with player movement, but I also needed a moveable player for testing.

To solve the problem I made a simplified character controller with far less functionality. In fact, the only functionality was movement. I called the script TempMovement.cs. In that script I made two major changes to how the player was being moved. For starters, I added a second update loop using Unity's FixedUpdate() method. This is different from the standard Update() method in that its cycle runs at a rate specified by the programmer, defaulting to 50 cycles per second. In contrast, Unity's regular Update() method completes a cycle every frame and is dependent on the hardware it runs on. For this reason, it made sense to check for input in the regular Update() loop and only update the player's position based on our specified speed in the FixedUpdate() loop.

The other issue was that holding down a vertical and horizontal key greatly increased the player's speed. This was because the two directional inputs being held down together caused the speed to be considered twice, doubling the speed of the player. The fix for this was to employ the sqrMagnitude() method of Unity's Vector2 class. This method returns the squared length of a vector. Using this allowed me to normalize the diagonal vector produced by simultaneously moving in the vertical and horizontal directions. The result was a much slower diagonal movement.

Although my script was never actually applied to the player character's prefab, the solutions I used were implemented directly into the CharacterController2DTopDown.cs script. That script controls everything the player is able to do. I'm glad to say I was able to contribute to it in some way.

Get City of Abominations (2021)

Leave a comment

Log in with itch.io to leave a comment.