EDIT: The script seems to work correctly if I don’t use a List and loop through the objects. But I don’t understand why I seemingly can’t use a List.
(method below is constantly running in Update)
void checkCollisions()
{
leftCornerLeft = Physics2D.Raycast(topLeftOrigin, Vector3.left, rayLength);
if(leftCornerLeft.collider != null)
{
//works as intended - if hitting collider this is sent, but if not this isn't sent
Debug.Log("hit!!!");
}
}
Original: I’m experimenting with keeping my player from being able to go through other gameobjects in a scene. Currently I’m simply using small raycasthit2Ds, sent out from positions close to the player’s collider - when one hits a collider, a Debug.Log is sent. (Eventually it’ll stop movement in the direction of the ray.)
However I’ve run into a problem - even when the ray isn’t hitting an object, Log messages are still being recorded. I think this has something to do with Update, perhaps the checkCollisions method is constantly creating new rays, but at the same time, something has to be constantly updated because otherwise the rays don’t move with the collider (ie, creating them in Start won’t update their positions).
Basically the Debug.Log messages don’t start until a collider is detected (like I want), but even when the when the rays stop hitting the collider, the messages keep getting sent (which I don’t want). I think the problem has to do with Update. The problem shouldn’t be the player’s own collider. Thanks for any help in advance.
RaycastHit2D leftCornerUp, leftCornerLeft;
List<RaycastHit2D> rays = new List<RaycastHit2D>();
float rayLength = 0.05f;
public CharacterMoveClamp charMoveClampScript;
Collider2D charCollider;
public void Start()
{
charCollider = GetComponent<Collider2D>();
}
// Update is called once per frame
void Update()
{
checkCollisions();
}
void checkCollisions()
{
//position the "up" raycast
Vector3 topLeftOrigin = new Vector3(charCollider.bounds.min.x, charCollider.bounds.max.y);
//use the CreateRaycasts method to create and return the raycast values
leftCornerLeft = CreateRaycasts(topLeftOrigin, Vector3.up);
leftCornerUp = CreateRaycasts(topLeftOrigin, Vector3.left);
//add the arrays to the list
rays.Add(leftCornerLeft);
rays.Add(leftCornerUp);
Debug.DrawLine(topLeftOrigin, new Vector3(topLeftOrigin.x, topLeftOrigin.y + rayLength), Color.cyan);
Debug.DrawLine(topLeftOrigin, new Vector3(topLeftOrigin.x - rayLength, topLeftOrigin.y), Color.cyan);
//loop through rays and see if any are hitting a collider
for (var i = 0; i < rays.Count; i++)
{
if (rays[i].collider != null)
{
Debug.Log("hit");
}
}
}
RaycastHit2D CreateRaycasts(Vector3 rayCoordinates, Vector3 rayDirection)
{
return Physics2D.Raycast(rayCoordinates, rayDirection, rayLength);
}
}