I’m still pretty new to Unity and just learned how to get diagonal movement working in a 2D space using the horizontal and vertical axes but I’m having trouble making the movement frame rate independent.
public class PlayerController : MonoBehaviour {
// Player's movement speed
public float moveSpeed = 2.0f * Time.deltaTime;
void Update() {
// Float value obtained from the horizontal and vertical axes
float movementInputX = Input.GetAxisRaw("Horizontal");
float movementInputY = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(movementInputX, movementInputY);
direction.Normalize();
direction *= moveSpeed;
transform.position += direction;
}
}
I’ve tried using Time.deltaTime where I initialized moveSpeed but got an error that read: “get_deltaTime is not allowed to be called from a MonoBehavior constructor (or instance field initializer), call it in Awake or Start instead.”
The issue is that Time.deltaTime is not a constant value. It represents the amount of time taken to render the previous frame. It will likely be slightly different every Update loop.
Say, for the sake of simple math, that your game runs at 60fps and you want to move your player 6 units per second. That means you need to move your player 6 units every 60 frames. So in 1 frame, that 0.1 units. That’s all well and good, but say something happens in your game that dips the frame rate for a quarter of a second. Now, for a short amount of time, the game is only running at 45fps. During those frames, the player should move 0.1333 units per frame.
To do this, when you multiply your direction by moveSpeed
you should also multiply it by Time.deltaTime
.
direction *= (moveSpeed * Time.deltaTime);
I’ve tried this but can’t seem to get more than a dead crawl out of my code:
public void Walk()
{
float controlFlowHorizontal = CrossPlatformInputManager.GetAxis("Horizontal"); //between -1 and +1
float controlFlowVertical = CrossPlatformInputManager.GetAxis("Vertical");
Vector2 PlayerVelocity = new Vector2(controlFlowHorizontal * walkSpeed * Time.deltaTime, controlFlowVertical * walkSpeed * Time.deltaTime);
myRigidBody.velocity = PlayerVelocity;
}
I’ve tried walkSpeeds from 75 - 3000 and no dice, it still just barely moves along