Character stuck on the wall

I code the movement for 2 characters at the same time in a grid movement, everything is fine but when 1 of the characters touches the wall, it will be stuck and can’t move, can anyone help me to finger out fix it, thank!

public class TestMoveRed : MonoBehaviour
{
[SerializeField]
float moveSpeed = 5f;

Vector3 targetPosition;
Vector3 startPosition;
bool moving;

void Update ()
{
if(moving)
{
if(Vector3.Distance(startPosition, transform.position) > 1f )
{
transform.position = targetPosition;
moving = false;
return;
}
transform.position += (targetPosition - startPosition) * moveSpeed * Time.deltaTime;
return;
}

if(Input.GetKeyDown(KeyCode.A))
{
targetPosition = transform.position + Vector3.left;
startPosition = transform.position;
moving = true;
}
else if(Input.GetKeyDown(KeyCode.D))
{
targetPosition = transform.position + Vector3.right;
startPosition = transform.position;
moving = true;
}
}
}

First, check the colliders, maybe they are too small.
Second, ALWAYS use Time.fixedDeltaTime in FixedUpdate and Time.deltaTime in Update, not mixed! (You should also only use FixedUpdate for Rigidbodies, and especially not for input, so change it to Update with Time.deltaTime.
Third, if the objects move too fast, Unity won’t be able to detect collisions, so try to decrease the fixed TimeStep in Edit - Project Settings - Time - Fixed Timestep to something like 0.005
Hope it helps!

1 Like

Thank you for helping me, i changed setting and code like you said but when character touch the wall, it’s will stick on the wall and cant move any direction. my colliders is big enough so that i dont think it is problem. Anyway thank for spend time to help me

Maybe check if both objects have non-trigger colliders and check if player has dynamic rigidbody and the wall no rigidbody. Also, making a target position isn’t a great mechanic, try to make
rigidbody.velocity += new Vector2(speedX * Time.fixedDeltaTime, speedY * Time.fixedDeltaTime);

1 Like

Thank you for helping me