1、座標系統的理解
(1)設備座標系
設備座標系的原點在顯示屏幕的左上角爲原點(0,0)。X軸右向爲正,Y軸是下向爲正,
(2)openGL座標系
openGL座標系以顯示屏幕左下角爲原點(0,0),Y軸是上向上正,X是右向爲正。
cocos2d-x以openGL庫繪製信息,採用openGL座標系。
(3)局部座標或本地座標
本地座標是相對座標,是以節點(node)的左下解爲原點(0,0)。
(4)世界座標
世界座標系又稱爲絕對座標系,是遊戲中虛擬出來的座標。表示場景空間內的統一座標系,用來標識遊戲的場景。它建立了其他座標系所需的參考標準,可使用世界系來描述其他座標系的位置。
(5)錨點
錨點是Cocos2d-x中一個非常重要的概念,每個節點都有一個錨點,錨點指定了紋理圖像和節點原點重合的位置。默認情況下,錨點位於紋理圖像的集合中心。錨點的最大作用是輔助節點進行界面佈局定位。
Node::setAnchorPoint(const Vec2& anchorPoint)
anchorPoint是規一化的座標, 取值0~1.可以理解爲百分比。
左下(0.0,0.0),
左上(1.0,0.0),
右上(1.0,1.0),
右下(1.0,0.0)
中心點(0.5, 0.5)
2、座標相關函數
(1)節點位置設定和取得
void Node::setPosition(float x, float y)
void Node::getPosition(float* x, float* y)
座標(x,y)是父節點的本地座標。
(2)錨點位置設定和取得
const Vec2& Node::getAnchorPoint()
void Node::setAnchorPoint(const Vec2& anchorPoint)
錨點缺省值爲(0,0),即節點的左下角。
設置值可以大於(1,1),或小於(0,0);
如果節點是一個物理體,錨點必須位置節點內部。
(3)座標系的轉化。
轉化爲節點座標,參數worldPoint爲世界座標
Vec2 Node::convertToNodeSpace(const Vec2& worldPoint)
轉化爲世界座標,參數nodePoint爲節點座標
Vec2 convertToWorldSpace(const Vec2& nodePoint)
3、繪製幾何圖
(1)繪製幾何圖形的程序框架
a.重載父類Node的draw()函數
void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags)
在draw()函數中寫繪製的回調函數OnMyDraw()
b.在OnMyDraw函數中繪製
畫點函數:drawPoint,drawPoints
畫線:drawLine
畫圓: drawCircle, drawSolidCircle
畫多邊形: drawPoly, drawSolidPoly
畫矩形:drawQuadBezier, drawCubicBezier
線寬:glLineWidth
顏色:setDrawColor
點大小:setPointSize
4、創建sprite
(1)創建sprite的函數
從文件中創建
Sprite* Sprite::create(const std::string& filename, const Rect& rect)
從動畫幀中創建
Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame)
從紋理中創建
Sprite* Sprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
從多邊形中創建
Sprite* Sprite::create(const PolygonInfo& info)
(2)設定sprite位置和錨點
void setAnchorPoint(const Vec2& anchor)
setPosition(const Vec2& pos)
setPosition(float x, float y)
(3)sprite縮放旋轉
void setRotation(float rotation)
void setScale(float scaleX, float scaleY)
(4)實戰紀錄
SpriteFrame* frame = SpriteFrame::create("HelloWorld.png", Rect(100, 100, 80, 80));
auto spriteByFrame = Sprite::createWithSpriteFrame(frame);
spriteByFrame->setAnchorPoint(Vec2(0, 1));// 指定錨點
spriteByFrame->setPosition(Vec2(0, visibleSize.height)); // 在左上角
this->addChild(spriteByFrame, 0);
5、實戰源碼分享
本文源碼在Debug-win32下編譯運行通過。
ZIP包中包含開發環境,下載解壓後可直接編譯運行。