I am making a top-down 2D game. I expect the player should stop moving after hitting a wall, and he can still move toward the other directions. But after adding the code below, the player just stops moving permanently.
public class MovingControl : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed = 10;
public bool canMove = true;
private void Awake()
{
rb=GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 moveVector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (canMove && moveVector != Vector2.zero)
{
rb.MovePosition(rb.position + moveVector * moveSpeed * Time.deltaTime);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
canMove=false;
}
}
The player has the MovingControl + RigidBody2D + Box collider2D Components, where the RigidBody2D is Kinematic and the Box collider2D “Is Trigger” . The wall has a static RigidBody2D and a Box collider2D (without “is Trigger”). They are on the same layer.
This code will stop the player from moving after hitting the wall. But the question is, the player cannot move again. I know the reason: the “canMove” variable was set to false, and it never has a chance to become true again.But I just didn’t know where to set the variable to true again.
This may be a very basic question. I am wondering what’s the most common method that everybody use?