# Raycast, Calculate Random Direction

Hi,

There is a Vector3 Position, and there is a target.

I need to Raycast from the position to target at a deviated Random Angle.

However, the Script below gave me Raycasted Random Square Area instead of a Circle.

Could someone guide me in how to get the Random Raycast to be inside the Circle?

``````Vector3 CalcBulletDirectionVec3( Transform attackTransform )
{
Vector3 targetTransformPos = GetTargetTransform().position;
Vector3 tempDir = targetTransformPos - attackTransform.position;

tempDir = tempDir.normalized;

tempDir = Quaternion.Euler(CalcRandomAngleRange()) * tempDir;

return tempDir;
}

Vector3 CalcRandomAngleRange()
{
float maxAngle = CalcMaxAngle();
return new Vector3(GetRandomRange(maxAngle), GetRandomRange(maxAngle), 0.0f);
}

float GetRandomRange( float maxAngle )
{
return Random.Range(-maxAngle, maxAngle);
}
``````

For a circle like you want, it is easier (for me anyway) to think of of the problem as having a maximum inaccuracy at a specified distance.

``````Vector3 CalcBulletDirectionVec3( Transform attackTransform )
{
Vector3 targetTransformPos = GetTargetTransform().position;
Vector3 tempDir = targetTransformPos - attackTransform.position;

tempDir = tempDir.normalized;

Vector3 crossDir = Vector3.Cross(tempDir, Vector3.up);
crossDir = Quaternion.AngleAxis(Random.Range(0.0f, 360.0f), tempDir) * crossDir;
crossDir = Random.Range(0.0f, maxDelta) * crossDir;
tempDir += crossDir;

return tempDir;
}
``````

‘maxDelta’ is the maximum amount from a perfect shot the ray will be at one unit from the origin of the vector. This code depends on having one vector that is not parallel to the ‘tempDir’ vector for use in the Vector3.Cross(). I’ve selected Vector3.up because usually games either don’t provide shooting directly up or shooting directly up is meaningless.

The way this code works is to first find a vector that is orthogonal to (at right angles to) ‘tempDir’. It then picks a random value between 0.0 and 360.0 and swings that vector around using ‘tempDir’ as the axis of rotation. Then it scales the vector between 0.0 and maxDelta. The result is then used to offset ‘tempDir’.

If you really want angles for some reason, you could use an AngleAxis rotations to swing the vector left/right and up/down, but the result would be square, not a circle.