Используйте Transform.TransformDirection
[* см. Ниже] , чтобы преобразовать направление "вперед" глаз из локального пространства в мировое пространство, затем используйте Quaternion.AngleAxis
, чтобы создать повороты влево и вправо, чтобы найти глаз направления.
Vector2 frontLocalDirection = new Vector2(0.7071f,0.7071f);
// or whatever the local "front" direction is.
private RaycastHit2D[] FillRaycastArray()
{
List<RaycastHit2D> RaycastList = new List<RaycastHit2D>();
Vector2 rayOrigin = animalTransform.position;
// will be converted to Vector2 later
Vector3 frontWorldDirection = animalTransform.TransformDirection(
frontLocalDirection);
for (int i = 0; i < genes.sightQuality; i++)
{
float eyeAngleOffset = genes.sightAngle / 2 + genes.sightWidth * i;
Vector2 rightEyeDirectionVector = Quaternion.AngleAxis(eyeAngleOffset,
Vector3.back) * frontWorldDirection;
Vector2 leftEyeDirectionVector = Quaternion.AngleAxis(eyeAngleOffset,
Vector3.forward) * frontWorldDirection;
Debug.DrawRay(rayOrigin, rightEyeDirectionVector, Color.red);
Debug.DrawRay(rayOrigin, leftEyeDirectionVector, Color.red);
int predatorLayer = 1 << 8;
predatorLayer = ~predatorLayer;
RaycastHit2D hitR = Physics2D.Raycast(rayOrigin, rightEyeDirectionVector, 20f,
predatorLayer);
RaycastHit2D hitL = Physics2D.Raycast(rayOrigin, leftEyeDirectionVector, 20f,
predatorLayer);
RaycastList.Add(hitR);
RaycastList.Add(hitL);
}
RaycastHit2D[] raycastArray = RaycastList.ToArray();
return raycastArray;
}
Если frontLocalDirection
будет выглядеть как Vector2.up
, вы можете использовать только одно из удобных полей Transform
, например transform.up
, вместо использования TransformDirection
. Например:
private RaycastHit2D[] FillRaycastArray()
{
List<RaycastHit2D> RaycastList = new List<RaycastHit2D>();
Vector2 rayOrigin = animalTransform.position;
// will be converted to Vector2 later
Vector3 frontWorldDirection = animalTransform.up;
for (int i = 0; i < genes.sightQuality; i++)
{
float eyeAngleOffset = genes.sightAngle / 2 + genes.sightWidth * i;
Vector2 rightEyeDirectionVector = Quaternion.AngleAxis(eyeAngleOffset,
Vector3.back) * frontWorldDirection;
Vector2 leftEyeDirectionVector = Quaternion.AngleAxis(eyeAngleOffset,
Vector3.forward) * frontWorldDirection;
Debug.DrawRay(rayOrigin, rightEyeDirectionVector, Color.red);
Debug.DrawRay(rayOrigin, leftEyeDirectionVector, Color.red);
int predatorLayer = 1 << 8;
predatorLayer = ~predatorLayer;
RaycastHit2D hitR = Physics2D.Raycast(rayOrigin, rightEyeDirectionVector, 20f,
predatorLayer);
RaycastHit2D hitL = Physics2D.Raycast(rayOrigin, leftEyeDirectionVector, 20f,
predatorLayer);
RaycastList.Add(hitR);
RaycastList.Add(hitL);
}
RaycastHit2D[] raycastArray = RaycastList.ToArray();
return raycastArray;
}