raycast method

  1. @override
void raycast(
  1. Raycaster raycaster,
  2. List<Intersection> intersects
)
override

Get intersections between a casted ray and this sprite. Raycaster.intersectObject will call this method. The raycaster must be initialized by calling Raycaster.setFromCamera before raycasting against sprites.

Implementation

@override
void raycast(Raycaster raycaster, List<Intersection> intersects) {
  _worldScale.setFromMatrixScale(matrixWorld);

  _viewWorldMatrix.setFrom(raycaster.camera.matrixWorld);
  modelViewMatrix.multiply2(
      raycaster.camera.matrixWorldInverse, matrixWorld);

  _mvPosition.setFromMatrixPosition(modelViewMatrix);

  if (raycaster.camera is PerspectiveCamera && material != null && material!.sizeAttenuation == false) {
    _worldScale.scale(-_mvPosition.z);
  }

  final rotation = material?.rotation ?? 0;
  double? sin, cos;

  if (rotation != 0) {
    cos = math.cos(rotation);
    sin = math.sin(rotation);
  }

  final center = this.center;

  transformVertex(_spritevA..setValues(-0.5, -0.5, 0), _mvPosition, center,_worldScale, sin, cos);
  transformVertex(_spritevB..setValues(0.5, -0.5, 0), _mvPosition, center,_worldScale, sin, cos);
  transformVertex(_spritevC..setValues(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);

  _spriteuvA.setValues(0, 0);
  _spriteuvB.setValues(1, 0);
  _spriteuvC.setValues(1, 1);

  // check first triangle
  Vector3? intersect = raycaster.ray.intersectTriangle(
      _spritevA, _spritevB, _spritevC, false, _intersectPoint);

  if (intersect == null) {
    // check second triangle
    transformVertex(_spritevB..setValues(-0.5, 0.5, 0), _mvPosition, center,_worldScale, sin, cos);
    _spriteuvB.setValues(0, 1);

    intersect = raycaster.ray.intersectTriangle(
        _spritevA, _spritevC, _spritevB, false, _intersectPoint);
    if (intersect == null) {
      return;
    }
  }

  final distance = raycaster.ray.origin.distanceTo(_intersectPoint);

  if (distance < raycaster.near || distance > raycaster.far) return;

  intersects.add(Intersection(
    distance: distance,
    point: _intersectPoint.clone(),
    uv: TriangleUtil.getUV(_intersectPoint, _spritevA, _spritevB,
        _spritevC, _spriteuvA, _spriteuvB, _spriteuvC, Vector2.zero()),
    object: this
  ));
}