Unfortunately, this is my first time using raycasts, so, I’m still pretty new to how they work, I’m currently trying to make a turn based dungeon game, and due to that, I can’t use a normal physics script to detect collision, so right now I’m trying to use raycasts to do it, although, when I press play, the console just spams the debug message “hitting stuff”, even though the player is facing away from the colliders in my scene (my player does not have a collider attached to them btw) and I can’t figure out what’s going wrong, here’s my script
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Either supply or we GetComponent<T>();")]
public Transform PlayerTransform;
public Animator animator;
Vector3 currentPosition;
Vector3 desiredPosition;
float CellSize = 1.0f;
float MoveSpeed = 5.0f;
void Start()
{
if (!PlayerTransform)
{
PlayerTransform = transform;
}
}
bool Moving()
{
Ray2D rayForward = new Ray2D(PlayerTransform.position, PlayerTransform.up);
if (Physics2D.Raycast(rayForward.origin, rayForward.direction, 1.75f))
{
Debug.Log("Hitting Stuff");
} else
{
Debug.Log("Not Hitting Stuff");
// move
currentPosition = Vector3.MoveTowards(currentPosition, desiredPosition, MoveSpeed * Time.deltaTime);
}
// done?
Vector3 d = currentPosition - desiredPosition;
return d.magnitude > 0.01f;
}
void DriveTransform()
{
PlayerTransform.position = currentPosition + new Vector3(18.46f, 12.53f, 0);
// if you're wondering, the arbitrary numbers above is just the spot I want my player to spawn
}
void ReadInput()
{
var x = Input.GetAxisRaw("Horizontal");
var y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal", x);
animator.SetFloat("Vertical", y);
if (x != 0)
{
animator.SetFloat("animSpeed", 1);
} else if (y != 0)
{
animator.SetFloat("animSpeed", 1);
} else
{
animator.SetFloat("animSpeed", 0);
}
if (x < -0.5f)
{
desiredPosition += Vector3.left * CellSize;
animator.SetFloat("HorizontalIdle", x);
animator.SetFloat("VerticalIdle", y);
}
else if (x > 0.5f)
{
desiredPosition += Vector3.right * CellSize;
animator.SetFloat("HorizontalIdle", x);
animator.SetFloat("VerticalIdle", y);
}
else if (y > 0.5f)
{
desiredPosition += Vector3.up * CellSize;
animator.SetFloat("HorizontalIdle", x);
animator.SetFloat("VerticalIdle", y);
}
else if (y < -0.5f)
{
desiredPosition += Vector3.down * CellSize;
animator.SetFloat("HorizontalIdle", x);
animator.SetFloat("VerticalIdle", y);
}
}
void Update()
{
if (!Moving())
{
ReadInput();
}
DriveTransform();
}
}
right now, I just need the script to disable movement in the direction the player is facing if the next tile they would step on is a collider, I am aware I did not write any code that disables movement in a specific direction, but I wasn’t exactly sure how I should handle that with raycast code;