CubeMath.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Godot;
  2. public partial class CubeMath : Node3D
  3. {
  4. private static PackedScene cubePointScene = ResourceLoader.Load<PackedScene>("res://assets/cube/cube_point.tscn");
  5. private bool _isParentReady = false;
  6. private Node2D _parent;
  7. private Node3D[] _cubePointsMath = new Node3D[27]; // The math node of each 2.5D cube point
  8. private Node3D[] _cubeMathSpatials = new Node3D[27]; // The CubeMath children that find position.
  9. public override void _Ready()
  10. {
  11. _parent = GetParent<Node2D>();
  12. // Initialize the cube
  13. for (int i = 0; i < 27; i++)
  14. {
  15. int a = (i / 9) - 1;
  16. int b = (i / 3) % 3 - 1;
  17. int c = (i % 3) - 1;
  18. Vector3 spatialPosition = 5 * (a * Vector3.Right + b * Vector3.Up + c * Vector3.Back);
  19. _cubeMathSpatials[i] = new Node3D();
  20. _cubeMathSpatials[i].Position = spatialPosition;
  21. _cubeMathSpatials[i].Name = "CubeMath #" + i + ", " + a + " " + b + " " + c;
  22. AddChild(_cubeMathSpatials[i]);
  23. }
  24. }
  25. public override void _Process(float delta)
  26. {
  27. if (Input.IsActionPressed("exit"))
  28. {
  29. GetTree().Quit();
  30. }
  31. if (Input.IsActionJustPressed("view_cube_demo"))
  32. {
  33. GetTree().ChangeScene("res://assets/demo_scene.tscn");
  34. return;
  35. }
  36. if (_isParentReady)
  37. {
  38. RotateX(delta * (Input.GetActionStrength("move_back") - Input.GetActionStrength("move_forward")));
  39. RotateY(delta * (Input.GetActionStrength("move_right") - Input.GetActionStrength("move_left")));
  40. RotateZ(delta * (Input.GetActionStrength("move_counterclockwise") - Input.GetActionStrength("move_clockwise")));
  41. if (Input.IsActionJustPressed("reset_position"))
  42. {
  43. Transform = Transform3D.Identity;
  44. }
  45. for (int i = 0; i < 27; i++)
  46. {
  47. _cubePointsMath[i].GlobalTransform = _cubeMathSpatials[i].GlobalTransform;
  48. }
  49. }
  50. else
  51. {
  52. // This code block will be run only once. It's not in _Ready() because the parent isn't set up there.
  53. for (int i = 0; i < 27; i++)
  54. {
  55. PackedScene myCubePointScene = cubePointScene.Duplicate(true) as PackedScene;
  56. Node25D cubePoint = myCubePointScene.Instantiate() as Node25D;
  57. cubePoint.Name = "CubePoint #" + i;
  58. _cubePointsMath[i] = cubePoint.GetChild<Node3D>(0);
  59. _parent.AddChild(cubePoint);
  60. }
  61. _isParentReady = true;
  62. }
  63. }
  64. }