61 lines
1.5 KiB
TypeScript
61 lines
1.5 KiB
TypeScript
import { _decorator, Component, Node, Graphics, Color, UITransform } from 'cc';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('Shadow2D')
|
|
export class Shadow2D extends Component {
|
|
|
|
@property(Node)
|
|
target: Node | null = null; // 角色节点
|
|
|
|
@property
|
|
shadowWidth: number = 60;
|
|
|
|
@property
|
|
shadowHeight: number = 20;
|
|
|
|
@property
|
|
shadowAlpha: number = 80; // 0-255
|
|
|
|
private shadowNode: Node | null = null;
|
|
|
|
start() {
|
|
if (!this.target) {
|
|
console.warn("Shadow2D: 未绑定角色节点 target");
|
|
return;
|
|
}
|
|
|
|
// 创建影子节点
|
|
this.shadowNode = new Node("Shadow");
|
|
let g = this.shadowNode.addComponent(Graphics);
|
|
this.target.addChild(this.shadowNode);
|
|
|
|
// 调整大小
|
|
let ui = this.shadowNode.addComponent(UITransform);
|
|
ui.setContentSize(this.shadowWidth, this.shadowHeight);
|
|
|
|
// 画椭圆
|
|
g.fillColor = new Color(0, 0, 0, this.shadowAlpha);
|
|
g.ellipse(0, 0, this.shadowWidth / 2, this.shadowHeight / 2);
|
|
g.fill();
|
|
|
|
// 放到角色脚下
|
|
this.shadowNode.setPosition(0, -this.target.getComponent(UITransform).height / 2);
|
|
}
|
|
|
|
update(dt: number) {
|
|
if (!this.shadowNode || !this.target) return;
|
|
|
|
if (!this.target.active) {
|
|
this.shadowNode.active = false;
|
|
return;
|
|
}
|
|
|
|
// 始终保持在角色底部(比如角色动画高度变化时也能跟随)
|
|
let ui = this.target.getComponent(UITransform);
|
|
|
|
if (!ui) return;
|
|
|
|
this.shadowNode.setPosition(0, -ui.height / 2);
|
|
}
|
|
}
|