I have a CharacterBody2D that I’m attempting to move in a tile-based fashion. So instead of moving smoothly, it just moves instantly.
I noticed that when pressing two keys at the same time to “move diagonally” (there are only the 4 cardinal directions programmed) that the CharacterBody2D sprite moves only partially, and not the full amount of pixels, leaving the character in a scuffed location. How do I prevent this behavior? I tried adding _isKeyPressed to no avail. Is there perhaps a way for me to use MoveAndCollide() that is just as snappy as using Position?
You make direction from keys and still use ActionJustPresed to all directions
var direction = Input.GetVector("move_west", "move_east", "move_north", "move_south");
I think you can remove direction because allow values between 0 and 1, alternative you cast to integer vector (Vector2I) to remove fractions but can require more work.
in East you can use Vector2.Right instead direction
if (Input.IsActionJustPressed("move_east") && !_isKeyPressed)
{
_isKeyPressed = true;
Position += Vector2.Right * TileSize;
Input.ActionRelease("move_east");
Optional you can optimize Vector2.Right * TileSize with constant or class variable like
public override void _PhysicsProcess(double delta)
{
Vector2 direction = Vector2.Zero;
if (Input.IsActionJustPressed("move_north"))
direction = Vector2.Up;
else if (Input.IsActionJustPressed("move_east"))
direction = Vector2.Right;
else if (Input.IsActionJustPressed("move_south"))
direction = Vector2.Down;
else if (Input.IsActionJustPressed("move_west"))
direction = Vector2.Left;
Position += direction * TileSize;
var screenSize = GetViewportRect().Size;
// Prevent Player from moving outside of screen.
Position = new Vector2(
Mathf.Clamp(Position.X, 8, screenSize.X - 16),
Mathf.Clamp(Position.Y, 12, screenSize.Y - 12)
);
}
For some reason my code was visually slowing down the character movement. With this block of code I could feel the character movement was much quicker. I think whatever was causing the slowdown in my application code is the reason for 2 keys to be able to be pressed at the same time. Thanks for your solution!