cocos2dx LayoutUtil

coco2dx 没有Util可以把一个对象摆放到另一个对象指定位置, 于是我只好自己创造一个:

/*
 * LayoutUtil.cpp
 *
 *  Created on: 2012-8-28
 *      Author: jie
 */
/**
 * 固定 target 对象不动, 使 from node 的 fromx, fromy 的点同 target, destx, desty 的点重合
 * 其中 fromx, fromy 是从node的外面按照 node的尺寸计算的一个点, 同  node 本身的 anchor 不同
 */
void layout(cocos2d::CCNode* from, float fromx, float fromy, cocos2d::CCNode* dest, float destx, float desty, float offsetx, float offsety) {
	float x, y;
	dest->getPosition(&x, &y);
	const cocos2d::CCSize size = dest->getContentSize();
	const cocos2d::CCPoint anchor = dest->getAnchorPoint();
	// target position
	x += dest->getScaleX() * (destx - anchor.x) * size.width;
	y += dest->getScaleY() * (desty - anchor.y) * size.height;

	// source position relative to source's anchor
	const cocos2d::CCSize ssize = from->getContentSize();
	const cocos2d::CCPoint sanchor = from->getAnchorPoint();
	float rx = from->getScaleX() * (fromx - sanchor.x) * ssize.width;
	float ry = from->getScaleY() * (fromy - sanchor.y) * ssize.height;

	from->setPosition(x - rx + offsetx, y - ry + offsety);
}

void layout(cocos2d::CCNode* from, float fromx, float fromy, cocos2d::CCNode* dest, float destx, float desty) {
	layout(from, fromx, fromy, dest, destx, desty, 0, 0);
}

/**
 * 同 layout 类似, 不过 from 是 target 对象的子元素, 也就是说 target 对象自身的缩放和anchor point将不会影响子元素的对齐
 */
void layoutIn(cocos2d::CCNode* from, float fromx, float fromy, cocos2d::CCNode* dest, float destx, float desty, float offsetx, float offsety) {
	const cocos2d::CCSize size = dest->getContentSize();
	// target position in target node
	float x = destx * size.width;
	float y = desty * size.height;

	// source position relative to source's anchor
	const cocos2d::CCSize ssize = from->getContentSize();
	const cocos2d::CCPoint sanchor = from->getAnchorPoint();
	float rx = from->getScaleX() * (fromx - sanchor.x) * ssize.width;
	float ry = from->getScaleY() * (fromy - sanchor.y) * ssize.height;
	from->setPosition(x - rx + offsetx, y - ry + offsety);
}

void layoutIn(cocos2d::CCNode* from, float fromx, float fromy, cocos2d::CCNode* dest, float destx, float desty) {
	layoutIn(from, fromx, fromy, dest, destx, desty, 0, 0);
}


其中 fromx, fromy 和 destx, desty 的意思再解释一下, 这些点都是比例, 取值 [0,1] 就可以代表物体的左边和右边. 它们的位置计算的起点是从 node 内部坐标系的 0, 0 开始的, 调用的时候不要受 node 自身 anchorpoint 的影响.

例如, 以下为伪代码, 不要纠结语法错误:
CCNode container = new CCNode();
container.setSize(800, 480);
container.setAnchorPoint(0, 0)
CCNode n1 = new CCNode();
n1.setSize(200, 100);
n1.setAnchorPoint(0, 0)
layout(n1, 0, 0, container, 0, 0);
// 调用结束后物体的 position = {0, 0}

CCNode n2 = new CCNode();
n2.setSize(200, 100);
n2.setAnchorPoint(0.5, 0.5)
layout(n2, 0, 0, container, 0, 0);
// 调用结束后物体的 position = {100, 50}, 但对于观察者来说, 如果你并不知道 n2 的anchorpoint = 0.5, 0.5 那么你自然的会认为 0, 0 就是代表 n2 所表示矩形区域的左下角. 


layout 方法调用后被操作的对象唯一改变的只是物体本身的 x,y, anchorpoint 等都不会改变. offsetx, offsety 是在完成 layout 操作之后物体在当前的位置上再叠加一个偏移量, 单位是绝对值, 不是比例.

猜你喜欢

转载自hurry07.iteye.com/blog/1665227