diff --git a/cocos/2d/CCCamera.cpp b/cocos/2d/CCCamera.cpp index 354bdcdb73..8d155f34e6 100644 --- a/cocos/2d/CCCamera.cpp +++ b/cocos/2d/CCCamera.cpp @@ -245,9 +245,27 @@ bool Camera::initOrthographic(float zoomX, float zoomY, float nearPlane, float f return true; } +void Camera::project(const Size& viewport, Vec3* src, Vec2* dst) const +{ + GP_ASSERT(src); + GP_ASSERT(dst); + + Vec4 clipPos; + getViewProjectionMatrix().transformVector(Vec4(src->x, src->y, src->z, 1.0f), &clipPos); + + GP_ASSERT(clipPos.w != 0.0f); + float ndcX = clipPos.x / clipPos.w; + float ndcY = clipPos.y / clipPos.w; + + dst->x = (ndcX + 1.0f) * 0.5f * viewport.width; + dst->y = (1.0f - (ndcY + 1.0f) * 0.5f) * viewport.height; +} + void Camera::unproject(const Size& viewport, Vec3* src, Vec3* dst) const { - assert(dst); + GP_ASSERT(src); + GP_ASSERT(dst); + Vec4 screen(src->x / viewport.width, ((viewport.height - src->y)) / viewport.height, src->z, 1.0f); screen.x = screen.x * 2.0f - 1.0f; screen.y = screen.y * 2.0f - 1.0f; diff --git a/cocos/2d/CCCamera.h b/cocos/2d/CCCamera.h index 37fbfeac6a..fdc1015bb0 100644 --- a/cocos/2d/CCCamera.h +++ b/cocos/2d/CCCamera.h @@ -132,8 +132,21 @@ public: const Mat4& getViewProjectionMatrix() const; /** - * Convert the specified point of viewport from screenspace coordinate into the worldspace coordinate. - */ + * convert the specified point of viewport from world-space coordinates into the screen-space coordinates. + * + * @param viewport The viewport size to use. + * @param src The world-space position. + * @param dst The screen-space position. + */ + void project(const Size& viewport, Vec3* src, Vec2* dst) const; + + /** + * Convert the specified point of viewport from screen-space coordinate into the world-space coordinate. + * + * @param viewport The viewport size to use. + * @param src The screen-space position. + * @param dst The world-space position. + */ void unproject(const Size& viewport, Vec3* src, Vec3* dst) const; /**