0
\$\begingroup\$

So what I am trying to do is to find a random point on the (green") arc around the enemy:

enter image description here

Sorry for the bad drawing but

  • Red (no go)
  • Green ( Points the allied can go to)

I know that unity has the following function:

Radius = 5;
_randomDirection = (Random.insideUnitCircle * _target.position).normalized;
Vector3 finalPosition = _target + _randomDirection + Radius;

However, this is for a full circle. How can I achieve the closest half circle?

\$\endgroup\$
3
\$\begingroup\$

Check if the point you get is on the far half-circle, and if it is, mirror it.

Radius = 5;
_randomDirection = (Vector3)(Random.insideUnitCircle).normalized;

Vector3 toTarget = _target.position - _source.position;
if (Vector3.Dot(toTarget, _randomDirection) > 0f) {
    _randomDirection = Vector3.Reflect(_randomDirection, toTarget);
}    

Vector3 finalPosition = _target.position + _randomDirection * Radius;

You can also create this vector from scratch using a random angle:

Vector2 fromTarget = (_source.position - _target.position).normalized;
Vector2 perpendicular = new Vector2(-fromTarget.y, fromTarget.x);

float angle = Random.Range(0, Mathf.PI);

Vector2 offset = fromTarget * Mathf.Sin(angle) + perpendicular * Mathf.Cos(angle);

Vector3 finalPosition = _target.position + (Vector3)(offset * Radius);
\$\endgroup\$
3
  • \$\begingroup\$ The first example you posted doesnt seem to work for some reason :( \$\endgroup\$ – Marc Rasmussen Feb 19 at 19:01
  • \$\begingroup\$ "Doesn't work" is not enough information to diagnose the problem. We'll need specific symptoms or test cases to be able to help you. \$\endgroup\$ – DMGregory Feb 19 at 19:07
  • 1
    \$\begingroup\$ Bright solution and should w0rk perfectly well though I might just negate instead of reflect as it's random anyway, saves 0.01 nanosec :-). \$\endgroup\$ – Stormwind 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.