- Home /
Using Trigonometry for Collision Detection
Okay, so for the past few days I have been trying to figure out how to use a sphereCast to restrict the movement of my player. The sphereCast essentially represents the players weapon and during certain states the length of that sphereCast needs to dictate the location the player can move to.
I am not the strongest at maths but I think I'm sort of on the right track, the main thing I'm struggling with at the moment is how to convert all of the values I've gotten from the trig stuff and convert that into some sort of usable position.
However I'm still not entirely sure if I'm going about this in the correct way, I have attached a diagram, granted an bad one, but a diagram none the less of what I am trying to achieve. And also the code that I am using to try and achieve this. If anyone has any insight on this or could at least point me in the right direction that would be great. Thanks, Luke.
RaycastHit hit;
Vector3 rayOrigin = Vector3.zero;
Vector3 oldCPos = Vector3.zero;
Vector3 nextCPos = Vector3.zero;
Quaternion oldRot;
oldCPos = cTransform.localPosition;
nextCPos = oldCPos + inputDirection;
cTransform.localPosition = nextCPos;
rayOrigin.x = mainCamera.transform.position.x;
rayOrigin.y = weaponScript.transform.position.y;
rayOrigin.z = mainCamera.transform.position.z;
if (Physics.SphereCast(rayOrigin, 0.1F, weaponScript.transform.forward, out hit, weaponScript.clearDistance, weaponScript.noPlayerMask))
{
hyp1 = Vector2.Distance(new Vector2(oldCPos.x, oldCPos.z), new Vector2(nextCPos.x, nextCPos.z));
angleA1 = Mathf.Acos(Mathf.Clamp(Vector3.Dot(transform.forward, hit.normal),-1.0F, 1.0F));
finalAdj = Mathf.Cos(angleA1) * hyp1;
hyp2 = Vector2.Distance(new Vector2(oldCPos.x + (cTransform.forward.x * weaponScript.clearDistance),
oldCPos.z + (cTransform.forward.z * weaponScript.clearDistance)), new Vector2(hit.point.x, hit.point.z));
angleA2 = angleA1;
finalOpp = Mathf.Sin(angleA2) * hyp2;
finalHyp = Mathf.Sqrt((finalAdj * finalAdj) + (finalOpp * finalOpp));
angleA3 = Mathf.Acos(finalAdj / finalHyp) * 57.29578F;
angleA1 *= 57.29578F;
finalAngleA = angleA1 - angleA3;
oldRot = cTransform.rotation;
cTransform.rotation = Quaternion.AngleAxis(finalAngleA, transform.forward);
inputDirection.x = cTransform.forward.x * finalHyp;
inputDirection.z = cTransform.forward.z * finalHyp;
cTransform.rotation = oldRot;
}