node3d.dart 1.63 KB
Newer Older
1
part of flutter_sprites;
2

3 4 5 6 7 8
/// An node that transforms its children using a 3D perspective projection. This
/// node type can be used to create 3D flips and other similar effects.
///
///     var myNode3D = new Node3D();
///     myNode3D.rotationY = 45.0;
///     myNode3D.addChild(new Sprite(myTexture));
9 10 11 12
class Node3D extends Node {

  double _rotationX = 0.0;

13
  /// The node's rotation around the x axis in degrees.
14 15
  double get rotationX => _rotationX;

16
  void set rotationX(double rotationX) {
17 18 19 20 21 22
    _rotationX = rotationX;
    invalidateTransformMatrix();
  }

  double _rotationY = 0.0;

23
  /// The node's rotation around the y axis in degrees.
24 25
  double get rotationY => _rotationY;

26
  void set rotationY(double rotationY) {
27 28 29 30
    _rotationY = rotationY;
    invalidateTransformMatrix();
  }

31 32
  double _projectionDepth = 500.0;

33
  /// The projection depth. Default value is 500.0.
34 35
  double get projectionDepth => _projectionDepth;

36
  void set projectionDepth(double projectionDepth) {
37 38 39 40
    _projectionDepth = projectionDepth;
    invalidateTransformMatrix();
  }

41
  @override
42 43 44 45
  Matrix4 computeTransformMatrix() {
    // Apply normal 2d transforms
    Matrix4 matrix = super.computeTransformMatrix();

46 47 48 49 50 51
    // Apply perspective projection
    Matrix4 projection = new Matrix4(1.0, 0.0, 0.0, 0.0,
                                     0.0, 1.0, 0.0, 0.0,
                                     0.0, 0.0, 1.0, -1.0/_projectionDepth,
                                     0.0, 0.0, 0.0, 1.0);
    matrix = matrix.multiply(projection);
52 53 54 55 56 57 58 59

    // Rotate around x and y axis
    matrix.rotateY(radians(_rotationY));
    matrix.rotateX(radians(_rotationX));

    return matrix;
  }
}