cocoscreator layout水平布局,添加元素会自动调整x轴坐标,可以让layout的元素用cc.tween沿着x轴水平方向移动吗?
这需求太奇怪了,又要让它自动布局,又要不按照布局自己移动走开,既然一定要tween移动,你直接生成在计算好的X坐标不就好了
这种你只能自己手动算好坐标再用tween实现那种效果。
/**
* 计算布局坐标
* @param nodeInfos 参与布局的节点信息
* @param limitX X轴数量限制 -1表示无限 默认-1
* @param spaceX X轴间隔 默认10像素
* @param spaceY Y轴间隔 默认10像素
* @param alignX X轴对其方式 0表示左对齐 0.5表示居中 1表示右对齐 默认0.5
* @param alignY Y轴对其方式 0表示上对齐 0.5表示居中 1表示下对齐 默认0.5
* @returns 节点坐标
*/
public static calcLayout(nodeInfos: Array<ICalcLayoutNodeParam>, limitX?: number, spaceX?: number, spaceY?: number, alignX?: number, alignY?: number) {
let result: Array<{ x: number, y: number }> = [];
if (!nodeInfos || nodeInfos.length == 0) return result;
if (limitX == undefined || limitX == null) {
limitX = -1;
}
if (spaceX == undefined || spaceX == null) {
spaceX = 10;
}
if (spaceY == undefined || spaceY == null) {
spaceY = 10;
}
if (alignX == undefined || alignX == null) {
alignX = 0.5;
}
if (alignY == undefined || alignY == null) {
alignY = 0.5;
}
let totalWidth = 0; //总宽度
let totalHeight = 0; //总高度
let singleHeight = 0;//单个高度
for (let i = 0, j = nodeInfos.length; i < j; i++) {
if (limitX != -1 && i >= limitX) {
break;
}
let info = nodeInfos[i];
totalWidth += info.width * info.scale.x;
if (i > 0) {
totalWidth += spaceX;
}
singleHeight = info.height * info.scale.y;
}
if (limitX != -1) {
let rowNum = Math.floor(nodeInfos.length / limitX);
if (nodeInfos.length % limitX != 0) {
rowNum += 1;
}
totalHeight = rowNum * singleHeight + (rowNum - 1) * spaceY;
} else {
totalHeight = singleHeight;
}
let startX = -alignX * totalWidth;
let curX = startX;
let curY = alignY * totalHeight;
for (let i = 0, j = nodeInfos.length; i < j; i++) {
let info = nodeInfos[i];
if (limitX != -1 && i % limitX == 0) {
//换行
curX = startX;
if (i != 0) {
curY -= info.height * info.scale.y + spaceY;
}
}
result[result.length] = { x: curX + info.anchor.x * info.width * info.scale.x, y: curY - (1 - info.anchor.y) * info.height * info.scale.y };
curX += info.width * info.scale.x + spaceX;
}
return result;
}
/**计算节点时节点的参数 */
export interface ICalcLayoutNodeParam {
width: number,
height: number,
anchor: cc.Vec2,
scale: cc.Vec3
}
/**
* 获得参与布局的节点的参数
* @param node
*/
public static getLayoutNodeParamsInChildren(container) {
if (!container?.isValid || container.children.length == 0) return;
let paramAry: Array<ICalcLayoutNodeParam> = [];
let children: Array<cc.Node> = container.children;
for (let i = 0, j = children.length; i < j; i++) {
let node = children[i];
if (!node.active) continue;
let param = this.getLayoutNodeParam(node);
if (!param) continue;
paramAry[paramAry.length] = param;
}
return paramAry;
}
/**
* 获得参与布局的节点的参数
* @param node
*/
public static getLayoutNodeParam(node: cc.Node) {
if (!node?.isValid) return;
let trans = node.getComponent(cc.UITransform);
if (!trans) return;
let rtn: ICalcLayoutNodeParam = {
width: trans.width,
height: trans.height,
anchor: trans.anchorPoint,
scale: node.scale,
}
return rtn;
}