node3d.dart 1.77 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
part of flutter_sprites;
6

7 8 9 10 11 12
/// 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));
13 14 15 16
class Node3D extends Node {

  double _rotationX = 0.0;

17
  /// The node's rotation around the x axis in degrees.
18 19
  double get rotationX => _rotationX;

20
  set rotationX(double rotationX) {
21 22 23 24 25 26
    _rotationX = rotationX;
    invalidateTransformMatrix();
  }

  double _rotationY = 0.0;

27
  /// The node's rotation around the y axis in degrees.
28 29
  double get rotationY => _rotationY;

30
  set rotationY(double rotationY) {
31 32 33 34
    _rotationY = rotationY;
    invalidateTransformMatrix();
  }

35 36
  double _projectionDepth = 500.0;

37
  /// The projection depth. Default value is 500.0.
38 39
  double get projectionDepth => _projectionDepth;

40
  set projectionDepth(double projectionDepth) {
41 42 43 44
    _projectionDepth = projectionDepth;
    invalidateTransformMatrix();
  }

45
  @override
46 47 48 49
  Matrix4 computeTransformMatrix() {
    // Apply normal 2d transforms
    Matrix4 matrix = super.computeTransformMatrix();

50 51 52 53 54
    // 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);
55
    matrix.multiply(projection);
56 57 58 59 60 61 62 63

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

    return matrix;
  }
}