I am relatively new to c# and Unity, and I am making a top-down 2d game.
i made a simple character controller, and i implemented simple collision, but for some reason, it will not detect any collision if the player is going down(also detects no collision when going down diagonally), and i have no idea why, could anyone shed some light on this for me?
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] private float speed = 1f;
//animation states
int walkDir;
bool isWalkingBool;
//movement vectors
private Vector3 lastMoveDir;
public Vector3 moveDir;
//currently unused, for button prompt later
bool isColliding;
private void Update() {
playerMovement();
}
private void playerMovement() {
//for constructing the vector
float movex = 0;
float movey = 0;
//getting input
if (Input.GetKey(KeyCode.W)) {
movey = 1f;
walkDir = 1;
}
if (Input.GetKey(KeyCode.S)) {
movey = -1f;
walkDir = 2;
}
if (Input.GetKey(KeyCode.A)) {
movex = -1f;
walkDir = 3;
}
if (Input.GetKey(KeyCode.D)) {
movex = 1f;
walkDir = 4;
}
//for animation
bool isIdle = movey == 0 && movex == 0;
//Movement vectors
moveDir = new Vector3(movex, movey);
lastMoveDir = moveDir;
//Calculated movementVector
Vector3 TargetMovePosition = transform.position + moveDir.normalized * speed * Time.deltaTime;
//collision
//raycast offset, for colliding around the player, and not at the center
float raycastOffset = 0.05f;
//raycast start position vector
Vector3 raycastStart = transform.position + moveDir.normalized * raycastOffset;
//create raycast
RaycastHit2D hit = Physics2D.Raycast(raycastStart, moveDir.normalized, speed * Time.deltaTime);
//if the raycast contacted a collider with the tag "solid" it will not move, otherwise it will output "Collided with solid"
if (hit.collider != null && hit.collider.CompareTag("solid")) {
Debug.Log("Collided with solid");
} else {
transform.position = TargetMovePosition;
}
//for animation
isWalkingBool = moveDir != Vector3.zero;
}
//unused, for triggers later
public int CheckForCollision() {
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.5f);
foreach (Collider2D collider in colliders) {
Debug.Log("Collider tag: " + collider.tag); // Print collider tag for debugging
if (collider.CompareTag("")) {
return 1;
}
}
return 0;
}
//for animation
public bool IsWalking() {
return isWalkingBool;
}
public int CurrentDir() {
return walkDir;
}
public Vector3 returnVector() {
return moveDir;
}
}