How to make gridbased movement while also using collision?
I'm making a 2D tile-based puzzle game, and this is my movement code:
public class PlayerMovement : MonoBehaviour {
private float moveSpeed;
public Vector2 gridSize;
public float animationSpeed;
public bool canMove;
private Rigidbody2D rb;
private float moveHorizontal;
private float moveVertical;
public bool slippery;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
moveSpeed = animationSpeed * gridSize.x;
moveHorizontal = CrossPlatformInputManager.GetAxisRaw("Horizontal");
moveVertical = CrossPlatformInputManager.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
if (canMove)
{
if (moveVertical != 0 || moveHorizontal != 0)
{
rb.velocity = new Vector2(moveSpeed * moveHorizontal, moveSpeed * moveVertical);
canMove = false;
StartCoroutine(stopPlayer());
}
}
}
private IEnumerator stopPlayer()
{
yield return new WaitForSeconds(gridSize.x / moveSpeed); // this should be the exact time it takes for the player to reach the next cell, but it doesn't work like that I'm afraid.
rb.velocity = Vector2.zero;
canMove = true;
rb.position = new Vector2(Mathf.Round(rb.position.x / gridSize.x) * gridSize.x,
Mathf.Round(rb.position.y / gridSize.y) * gridSize.y); //this just snaps the player to the closest grid cell.
}
}
now I'm using physics and rigidbody simply because I want the player to register collisions, but that also causes the behavior to be funky and unpredictable, especially when you're dealing with different devices all at once. For example, when played on an iPhone, the player will collide with the next cell before stopping and snapping to grid. What can I do differently ?
Comment