When I run my program this script below is to control movement and collision on the x axis, however, for some unknown reason the player stops further from walls on one side compared to the other (shown in attached images). Would anyone know how to make it so the player stops a consistent distance from walls on both sides? Also I’m using unity’s tilemap system for the map.
public class PlayerMovement : MonoBehaviour
{
Vector3 moveDelta;
[SerializeField]
float movementSpeed;
[SerializeField]
float jumpHeight;
[SerializeField]
GameObject player;
RaycastHit2D hit;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && player.GetComponent<Gravity>().ground.collider != null)
{
transform.position += new Vector3(0, 0.2f, 0);
player.GetComponent<Gravity>().falling = -jumpHeight;
}
}
private void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
moveDelta = new Vector3(x * Time.deltaTime * movementSpeed, 0, 0);
hit = Physics2D.BoxCast(transform.position + new Vector3(0,0.1f,0), new Vector2(1f, 1.8f), 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.x), LayerMask.GetMask("Ground"));
Debug.Log(moveDelta);
if (hit.collider == null)
{
transform.Translate(moveDelta);
}
}
}
TIA