cocos2d 坐标系统参考

Cocos2D坐标系统参考

iOS两种坐标系统

iOS两种坐标系统

UIKit以左上角为原点,Core Graphics(Quartz 2D), Core Animation, OpenGL ES以左下角为原点。

Cocos2D坐标系

iOS版Cocos2D基于OpenGL ES,和OpenGL ES坐标系相同: 原点在屏幕左下角,X向右正向增长,Y向上正向增长。

anchorPoint: 定位参考点

anchorPoint是定位某个长方形(CALayer, CCLayer, CCSprite…)时的定位参考点。

anchorPoint定义

anchorPoint定义

anchorPoint在进行定位、旋转、缩放时发挥重要作用。

anchorPoint用途

anchorPoint用途

position: 相对坐标和绝对坐标

Cocos2D中的节点(CCNode)也是分层树状组织在一起,每一个节点有且只有一个父节点(self.parent),0个或者多个子节点(self.children),每个字节点都以自己的父节点的anchorPoint为坐标原点定义的坐标系来进行定位,即self.position。这种做法和UIKit(UIView)的结构一模一样。

mySprite.position: 精灵mySprite相对于父节点(mySprite.parent)的坐标值

CGPoint worldLocation = [mySprite convertToWorldSpace:mySprite.position];

worldLocation: 精灵mySprite相对于所属场景(CCScene)的坐标值,也是绝对坐标值。

Cocos2d中一段非常有用的代码解析:

从UITouch对象获得在Cocos2d坐标系中的触摸位置(相对坐标) - (CGPoint)convertTouchToNodeSpace:(UITouch *)touch { //uiLocation:UIKit坐标系表示的相对坐标值( 以屏幕左上角为原点,Y轴向下,X轴向右) CGPoint uiLocation = [touch locationInView:[touch view]];  //worldLocation:OpenGL坐标系表示的绝对坐标值(以屏幕左下角为原点,Y轴向上,X轴向右) CGPoint worldLocation = [[CCDirector sharedDirector] convertToGL:uiLocation]; //localLocation:OpenGL坐标系表示的相对坐标值(以父节点anchorPoint为原点,Y轴向上,X轴向右) CGPoint localLocation = [self convertToNodeSpace:worldLocation]; return localLocation; // coordinate relative to node's parent } //父节点的anchorPoint在"父节点的父节点中的相对坐标值":self.parent.anchorPointInPoints
原文地址:https://www.cnblogs.com/PursuitOnly/p/2871597.html