I have a KinematicBody2D for a character scene and I’m using MoveAndCollide for the movement. The character collides and stops, but it does not slide against the collisions with a diagonal input ( Top and Left, Top and Right… ). I tried using MoveAndSlide but the character didn’t even budge.
Is there a way to make the character slide against collision with diagonal input whilst still detecting the collision?
Explain why the code examples didn’t work. What went wrong then?
As an example, why did code from the following snippet not work for you?
using Godot;
using System;
public class KBExample : KinematicBody2D
{
private PackedScene _bullet = (PackedScene)GD.Load("res://Bullet.tscn");
public int Speed = 200;
private Vector2 _velocity = new Vector2();
public void GetInput()
{
// add these actions in Project Settings -> Input Map
_velocity = new Vector2();
if (Input.IsActionPressed("backward"))
{
_velocity = new Vector2(-Speed/3, 0).Rotated(Rotation);
}
if (Input.IsActionPressed("forward"))
{
_velocity = new Vector2(Speed, 0).Rotated(Rotation);
}
if (Input.IsActionPressed("mouse_click"))
{
Shoot();
}
}
public void Shoot()
{
// "Muzzle" is a Position2D placed at the barrel of the gun
var b = (Bullet)_bullet.Instance();
b.Start(GetNode<Node2D>("Muzzle").GlobalPosition, Rotation);
GetParent().AddChild(b);
}
public override void _PhysicsProcess(float delta)
{
GetInput();
var dir = GetGlobalMousePosition() - GlobalPosition;
// Don't move if too close to the mouse pointer
if (dir.Length() > 5)
{
Rotation = dir.Angle();
_velocity = MoveAndSlide(_velocity);
}
}
}
As a sidenote to other people that stumble upon this topic:
Unlike MoveAndCollide(), MoveAndSlide() multiplies the input parameter by delta for you. The similarities between the two functions (in Godot v3) make users prone to assume that the parameter should be the same. In Godot v4, the MoveAndSlide() function operates a little differently (I assume to avoid this confusion).