Thank you for dropping by my post, I have a problem with raycasts that I just can’t solve! The way my code is supposed to work is that, it shoots out a ray from the players “magiccaster” to the crosshair, and if it hits something, it gets the point that it hit, shoots it back to the players magic caster, and if it runs into the player on the way, it means that the raycast point is behind the player so it then ignores the first object it ran into, and raycast through it. Or atleast, thats how it should work. my problem is that the raycast is completely inconsisten, jumping all over the place! if someone could help me, that would be much appreciated, as ive been strugglng on this for awhile.
Code:
mouseWorldPosition = Vector3.zero;
Debug.DrawRay(playerController.cameraTransform.position, playerController.cameraTransform.forward * raycastDistance, Color.green);
Vector2 crosshairAimPoint = new Vector2(Screen.width / 2f, Screen.height / 2f);
Ray ray = Camera.main.ScreenPointToRay(crosshairAimPoint);
if(Physics.Raycast(ray, out RaycastHit raycastHit, raycastDistance, ~RaycastIgnore))
{
Vector3 playerAimCheck = magicCasterTransform.position - raycastHit.point;
if (Physics.Raycast(raycastHit.point, playerAimCheck, out RaycastHit hitPoint, ThroughPlayer))
{
if (hitPoint.collider.gameObject.layer == 6)
{
LayerMask oldLayer = raycastHit.collider.gameObject.layer;
GameObject oldObject = raycastHit.collider.gameObject;
raycastHit.collider.gameObject.layer = 8;
if (Physics.Raycast(ray, out RaycastHit newRaycastHit, raycastDistance, ~RaycastIgnore))
{
Vector3 newPlayerAimCheck = magicCasterTransform.position - newRaycastHit.point;
Debug.DrawRay(newRaycastHit.point, newPlayerAimCheck, Color.blue);
aimVis.transform.position = newRaycastHit.point;
mouseWorldPosition = newRaycastHit.point;
}
else
{
aimVis.transform.position = playerController.cameraTransform.position + playerController.cameraTransform.forward * raycastDistance;
mouseWorldPosition = playerController.cameraTransform.position + playerController.cameraTransform.forward * raycastDistance;
}
oldObject.layer = oldLayer;
}
else
{
Debug.DrawRay(raycastHit.point, playerAimCheck, Color.red);
Debug.Log("Hitting player");
aimVis.transform.position = raycastHit.point;
mouseWorldPosition = raycastHit.point;
}
}
else
{
Debug.DrawRay(raycastHit.point, playerAimCheck, Color.red);
Debug.Log("Not Hitting Player");
aimVis.transform.position = raycastHit.point;
mouseWorldPosition = raycastHit.point;
}
}
else
{
aimVis.transform.position = playerController.cameraTransform.position + playerController.cameraTransform.forward * raycastDistance;
mouseWorldPosition = playerController.cameraTransform.position + playerController.cameraTransform.forward * raycastDistance;
}
Here’s also a video with my problem:
Thanks in advance!