之前困扰过, 学习了几篇文章和动手实际操作了一下.理清楚了, 其实很简单.
如下图所示: player为一个空物体坐标(-197,-77),子物体star是图中的星星.坐标(0,0) 脚本zuobiao.ts绑定在Canvas上.
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
playerNode:cc.Node = null;
starNode:cc.Node = null;
// LIFE-CYCLE CALLBACKS:
onLoad () {
this.playerNode = cc.find('Player', this.node);
this.starNode = cc.find('Player/star', this.node);
}
start () {
this.test();
}
// update (dt) {}
test()
{
let starWorldPos = this.playerNode.convertToWorldSpaceAR(this.starNode.position);
let localPos = this.node.convertToNodeSpaceAR(starWorldPos);
console.log('PlayerPos: ', this.playerNode.position);
console.log('StarPos: ', this.starNode.position);
console.log('localPos: ', localPos);
}
}
startWorldPos: 把player节点下的星星节点转化为世界坐标.(由于星星坐标和player相同, 换句话说把player自身本地坐标转换为世界坐标)
localPos: 把世界坐标转化为节点下的子坐标.(this.node 指的是Canvas)
打印出来的日志如下如所示: