Tilemap Coliider 2D doesn't trigger on Y axis
Hello, I'm just starting to learn Unity.
I'm watching this tutorial on making a 2D game, it's a little old and some things changed in the UI but I made my best to do every step up to 1:29:55, where my problem appears.
I have a player_0 with BoxCollider2D, TEST_NPC with BoxCollider2D and a Tilemap with TilemapCollider. The Tilemap is on Layer named "Blocking", player and NPC are on Layer named "Actor".
Following script is what I'm using for move and simple collision detection, but as player collides with NPC properly, it collides with walls on "Blocking" Layer only on X axis. Y axis doesn't trigger a hit at all.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float movementSpeed = 2.0f;
private BoxCollider2D boxCollider;
private Vector3 moveDelta;
private RaycastHit2D hit;
private void Start()
{
boxCollider = GetComponent<BoxCollider2D>();
}
private void FixedUpdate()
{
moveDelta = Vector3.zero;
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
moveDelta = new Vector3(x, y, 0);
if (moveDelta.x > 0) {
transform.localScale = Vector3.one;
} else if (moveDelta.x < 0) {
transform.localScale = new Vector3(-1, 1, 0);
}
Vector3 boxPosition = new(transform.position.x + boxCollider.offset.x, transform.position.y + boxCollider.offset.y, 0);
Debug.Log(boxPosition);
hit = Physics2D.BoxCast(
boxPosition,
boxCollider.size,
0,
new Vector2(moveDelta.x, 0),
Mathf.Abs(moveDelta.x * Time.deltaTime),
LayerMask.GetMask("Actor", "Blocking")
);
if (hit.collider == null)
{
transform.Translate(movementSpeed * (moveDelta.x * Time.deltaTime), 0, 0);
}
hit = Physics2D.BoxCast(
boxPosition,
boxCollider.size,
0,
new Vector2(0, moveDelta.y),
Mathf.Abs(moveDelta.y * Time.deltaTime),
LayerMask.GetMask("Actor", "Blocking")
);
if (hit.collider == null)
{
transform.Translate(0, movementSpeed * (moveDelta.y * Time.deltaTime), 0);
}
}
}
The Collision Tilemap in my example is just these 2 squares for test purposes, as you see I use really default values and X and Y axes should work the same. Player looks like this (NPC is the same, without Player script): Please advice, I'm a little confused about why would the Y axis work differently to X axis.
I found out what's wrong. I updated the moveDelta by movementSpeed paramenter after asserting the hitbox, so It wen't right through them on axis that is shorter.