NeHe OpenGL Lesson48 - ArcBall Rotation (Mouse Rotation)
This sample provides us an ArcBall module that we could use to rotate object along the screen with mouse. The underneath idea is mapping a 2d screen position into a 3d sphere coordinate. A rotation Quat could be calculated out by two sphere coordinates (the start, end position). Then a rotation matrix created based on the quat.
This sample also provide some other useful technologies:
1) convert quat to a rotation matrix;
2) use OpenGL fucntion “glMultMatrixf(Transform.M);”to set up the model view matrix directly;
Mapping 2D Mouse Position into 3D Sphere Coordinate
At first we simply scale down the mouse coordinates from the range of [0...width), [0...height) to [-1...1], [1...-1] (Y flipped).
X = (MousePt.X / ((Width - 1) / 2)); Y = -(MousePt.Y / ((Height - 1) / 2));
Calculate the 3D Sphere coordinates:
length = (X * X) + (Y * Y); //If the point is mapped outside of the sphere... (length > radius squared) if (length > 1.0f) { GLfloat norm; //Compute a normalizing factor (radius / sqrt(length)) norm = 1.0f / FuncSqrt(length); //Return the "normalized" vector, a point on the sphere NewVec->s.X = TempPt.s.X * norm; NewVec->s.Y = TempPt.s.Y * norm; NewVec->s.Z = 0.0f; } else //Else it's on the inside { //Return a vector to a point mapped inside the sphere sqrt(radius squared - length) NewVec->s.X = TempPt.s.X; NewVec->s.Y = TempPt.s.Y; NewVec->s.Z = FuncSqrt(1.0f - length); }
The full source code could be found here.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了