draw spherecast unity code example
Example 1: unity spherecast
void CheckSpherecast(float radius, float detectableDistance, LayerMask detectableLayer) {
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.SphereCast(ray, radius, out hitInfo, detectableDistance, detectableLayer)) {
Debug.Log(hitInfo);
}
}
Example 2: draw sphere cast unity with program
void RenderVolume(Vector3 p1 , Vector3 p2 , float radius , Vector3 dir, float distance )
{
if (!shape)
{
shape = GameObject.CreatePrimitive(PrimitiveType.Cube).transform;
Destroy(shape.GetComponent<Collider>());
shape.GetComponent<Renderer>().material = mat;
}
Vector3 scale ;
float diam = 2 * radius;
scale.x = diam;
scale.y = Vector3.Distance(p2, p1) + diam;
scale.z = distance + diam;
shape.localScale = scale;
shape.position = (p1 + p2 + dir.normalized * distance) / 2;
shape.rotation = Quaternion.LookRotation(dir, p2 - p1);
shape.GetComponent<Renderer>().enabled = true;
}
void HideVolume()
{
if (shape) shape.GetComponent<Renderer>().enabled = false;
}
private Transform shape ;
public float range = 10;
private float freeDistance = 0;
void Update()
{
if (Input.Get$$anonymous$$ey("p"))
{
RaycastHit hit;
CharacterController charContr = GetComponent<CharacterController>();
var radius = charContr.radius;
Vector3 p1 = transform.position + charContr.center;
var p2 = p1;
var h = charContr.height / 2 - radius;
p2.y += h;
p1.y -= h;
RenderVolume(p1, p2, radius, transform.forward, range);
if (Physics.CapsuleCast(p1, p2, radius, transform.forward,out hit, range))
{
freeDistance = hit.distance;
}
else {
freeDistance = range;
}
}
if (Input.Get$$anonymous$$eyUp("p"))
{
HideVolume();
}
}