代码如下
import { _decorator, Camera, Component, Node, UITransform, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('test')
export class test extends Component {
@property(Node)
targetNode: Node = null; // 3D 物体
@property(Camera)
mainCamera: Camera = null; // 3D 摄像机
@property(Node)
uiNode: Node = null; // 2D 跟随的 Sprite (UI)
@property(Node)
canvasNode: Node = null; // UI 的 Canvas 节点
private screenPos = new Vec3();
private uiPos = new Vec3();
update() {
if (!this.targetNode || !this.mainCamera || !this.uiNode || !this.canvasNode) {
console.error("缺少 targetNode, mainCamera, uiNode 或 canvasNode");
return;
}
// **1. 获取 3D 物体的世界坐标**
let worldPosition = this.targetNode.worldPosition;
// **2. 转换为屏幕坐标**
this.mainCamera.worldToScreen(worldPosition, this.screenPos);
// **3. 将屏幕坐标转换为 Canvas 的 UI 坐标**
let canvasUI = this.canvasNode.getComponent(UITransform);
if (!canvasUI) {
console.error("Canvas 缺少 UITransform 组件");
return;
}
// 屏幕坐标 -> Canvas 内的 UI 坐标
canvasUI.convertToNodeSpaceAR(new Vec3(this.screenPos.x, this.screenPos.y, 0), this.uiPos);
// **4. 更新 UI 节点的位置**
this.uiNode.setPosition(this.uiPos);
}
}




。不造是我api用法有问题还是其他的什么用法错误。还是得用矩阵算么