CubeInfo.ts 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { _decorator, Component, Node, Vec3, Material, MeshRenderer, Vec4 } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('CubeInfo')
  4. export class CubeInfo extends Component {
  5. // 方块在 map 中的坐标
  6. private PosX: number = -1;
  7. private PosY: number = -1;
  8. private PosZ: number = -1;
  9. private id: number = -1; // 方块 id
  10. @property(Material)
  11. private mater: Material; // 方块材质
  12. private lock: boolean; // 是否解锁
  13. @property(Material) // 引用消融材质
  14. dissolveMaterial: Material = null;
  15. private dissolveThreshold: number = 0.0; // 消融阈值
  16. private dissolveSpeed: number = 1.0 / 3.0; // 每秒增加的消融值,确保3秒消融完成
  17. private isDissolving: boolean = false;
  18. private _originalMaterial: Material = null;
  19. start() {
  20. }
  21. setOriginalMaterial(material: Material) {
  22. this._originalMaterial = material;
  23. }
  24. public triggerDissolve() {
  25. if (!this.isDissolving) {
  26. this.isDissolving = true;
  27. this.dissolveThreshold = 0.0;
  28. this.getComponentInChildren(MeshRenderer).setMaterialInstance(this.dissolveMaterial, 0);
  29. }
  30. }
  31. update(deltaTime: number) {
  32. if (this.isDissolving) {
  33. // 通过消融速度更新消融阈值,3秒内完成
  34. this.dissolveThreshold += this.dissolveSpeed * deltaTime;
  35. console.log("Dissolve Threshold:", this.dissolveThreshold);
  36. // 控制消融速度,使其平滑
  37. if (this.dissolveThreshold >= 1.0) {
  38. this.dissolveThreshold = 1.0;
  39. // 恢复原始材质
  40. this.getComponentInChildren(MeshRenderer).setMaterialInstance(this._originalMaterial, 0);
  41. this.isDissolving = false;
  42. }
  43. // 获取方块的世界坐标
  44. const worldPos = this.node.getWorldPosition();
  45. console.log("World Position:", worldPos); // 输出世界坐标
  46. // 将 Vec3 转换为 Vec4,最后一位设置为 1.0
  47. const objectCenter = new Vec4(worldPos.x, worldPos.y, worldPos.z, 1.0);
  48. // 将方块位置传递给 Shader,作为 objectCenter
  49. this.dissolveMaterial.setProperty('objectCenter', objectCenter);
  50. // 更新消融阈值到材质中
  51. this.dissolveMaterial.setProperty('dissolveThreshold', this.dissolveThreshold);
  52. }
  53. }
  54. public setPos(x: number, y: number, z: number) {
  55. this.PosX = x;
  56. this.PosY = y;
  57. this.PosZ = z;
  58. }
  59. public getPos(): Vec3 {
  60. return new Vec3(this.PosX, this.PosY, this.PosZ);
  61. }
  62. public setId(value: number) {
  63. this.id = value;
  64. }
  65. public getId() {
  66. return this.id;
  67. }
  68. public getLock() {
  69. return this.lock;
  70. }
  71. public setLock(value: boolean) {
  72. this.lock = value;
  73. }
  74. public getMaterial() {
  75. return this.mater;
  76. }
  77. public setMaterial(value: Material) {
  78. this.mater = value;
  79. }
  80. }