OpenGL---箱子沿斜面下滑

21 篇文章 1 订阅
12 篇文章 0 订阅

假设箱子只受重力。

#include <windows.h> 
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
#include "math.h"
#include "vector2.h"

#pragma comment(lib, "glut.lib")

const int windowWidth = 800;
const int windowHeight = 600;

const double    rads_per_deg = 0.01745;  //度换算成弧度
const double    pixels_per_meter = 10;   //米换算成像素
const double    g           = 9.81;      //重力加速度 9,81 m/s^2
double          theta       = 30;        //坡度

double      mass    = 1;        //箱子的重量,1kg
bool simulation_over = false;   //箱子移动是否结束
double  box_pos = 0;            //箱子的位置
double  box_vel = 0;            //箱子的速度
Vector2         force_grav;     //箱子所受重力

LARGE_INTEGER   clock_freq;   
LARGE_INTEGER   last_time;

void myDisplay(void) 
{ 
    glClear(GL_COLOR_BUFFER_BIT);  //清屏
    glColor3f( 1, 1, 1 );

    //箱子所受重力
    force_grav.x = mass * g * sin( theta * rads_per_deg );
    force_grav.y = -mass * g * cos( theta * rads_per_deg );

    LARGE_INTEGER i;
    QueryPerformanceCounter( &i );
    double elapsed_time = double( i.QuadPart - last_time.QuadPart ) / clock_freq.QuadPart;
    last_time = i;

    if(! simulation_over ) 
    {
        //F = ma -> a = F/m
        double acc = force_grav.x / mass;    //加速度
        box_vel += ( acc * elapsed_time );   //速度
        box_pos += ( box_vel * pixels_per_meter ) * elapsed_time;  //位置
    }

    if( box_pos >= 600 ) 
    {
        simulation_over = true;
    }

    //地面
    glBegin( GL_LINES );
        glVertex2i( 700, 100 );
        glVertex2i( 100, 100 );
    glEnd();

    double dw = 600;    //斜面,原始位置为(700,100)

    glPushMatrix();  

        //原点
        glTranslatef( 700, 100, 0 );
        glRotatef( -theta, 0, 0, 1);

        //斜坡
        glBegin( GL_LINES );
            glVertex2i( 0, 0 );
            glVertex2i( -dw, 0 );
        glEnd();

        //箱子的位置
        glTranslatef( box_pos-dw, 50, 0 );

        //箱子
        glBegin( GL_LINE_LOOP );
            glVertex2i( -50, 50 );
            glVertex2i( 50, 50 );
            glVertex2i( 50, -50 );
            glVertex2i( -50, -50 );
        glEnd();

    glPopMatrix();

    glutSwapBuffers();
    glutPostRedisplay();
} 

void myInit()
{
    glMatrixMode( GL_PROJECTION ); 
    glLoadIdentity();
    gluOrtho2D( 0, windowWidth, 0, windowHeight );

    glClearColor(0, 0, 0, 0);      //背景颜色是黑色
    glViewport(0, 0, windowWidth, windowHeight);
}

int main(int argc, char *argv[]) 
{ 
    if( QueryPerformanceFrequency( &clock_freq ) ) 
    {
        QueryPerformanceCounter( &last_time );
        glutInit(&argc, argv); 
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); 
        glutInitWindowPosition(50, 50); 
        glutInitWindowSize(windowWidth, windowHeight);
        glutCreateWindow("DEMO"); 
        myInit();
        glutDisplayFunc(myDisplay); 
    }
    glutMainLoop(); 
    return 0; 
}

vector2.h

#ifndef _Vector2_H
#define _Vector2_H

#include <cmath>
#include <iostream>

using namespace std;

class Vector2 
{
public:

    // vars
    float x, y;

    // constructors
    Vector2() {}

    Vector2( float x1, float y1 ) : x(x1), y(y1) {}

    // vector ops
    void normalize() 
    {
        float temp = 1 / length();

        x *= temp;
        y *= temp;
    }

    inline double length() const 
    {
        return( sqrt((x * x) + (y * y)) );
    }

    Vector2 perp() const 
    {
        return( Vector2( y, -x ) );
    }

    //  operators
    Vector2 operator + ( const Vector2 & rhs ) const 
    {
        return( Vector2(x + rhs.x, y + rhs.y) );
    }

    Vector2 operator - ( const Vector2 & rhs ) const 
    {
        return( Vector2( x - rhs.x, y - rhs.y ) );
    }

    Vector2 operator / ( float k ) const 
    {
        return( Vector2(x / k, y / k) );
    }

    float operator * ( const Vector2 & rhs ) const 
    {
        // dot product
        return( (x * rhs.x) + (y * rhs.y) );
    }

    Vector2 operator * ( const float & rhs ) const 
    {
        // scale by scalar
        return( Vector2( x * rhs, y * rhs ) );
    }

    bool operator == ( const Vector2 & rhs ) 
    {
        return( rhs.x == x && rhs.y == y );
    }

    friend Vector2 operator * ( const float & lhs, const Vector2 & rhs ) 
    {
        // scale by scalar
        return( Vector2( rhs.x * lhs, rhs.y * lhs ) );
    }

    friend istream & operator >> ( istream & i, Vector2 & v ) 
    {
        i >> v.x >> v.y;
        return( i );
    }

    friend ostream & operator << ( ostream & o, Vector2 & v ) 
    {
        o << v.x << " " << v.y;
        return( o );
    }

}; // end class

#endif // _Vector2_H

这里写图片描述

主要是模拟初中的物理实验的有源代码,可供初学者使用! 采用 MFC 编制 MVC 模式之球体演示程序 作者:haykey 下载源代码   在传统面向过程的程序设计中,往往采用 Input-Processing-Output 模式,这“归功”于 DOS 操作系统的单任务。当 Windows 图形界面 OS 出现后,MVC(Model-View-Controller)模型更适合 Windows 图形界面程序的设计,它将数据处理和数据显示分离开,使维护,扩展系统更加灵活 。其中,View:负责 显示数据,它从Model处获得数据然后显示。当然,一个Model会有用户可从不同角度来观察的多个View。Model:存储数据以及对数据进行各种运算和处理 。Controller:负责接受用户输入,并且把用户输入转换成对 Model 的操作。因此Controller 可能会修改 Model 的数据,当数据修改后,更新 View。其结构示意图如下:   一直采用MFC编程的朋友可能不太熟悉它,这是因为MFC的文档视图结构就是基于MVC的高层结构,这蒙蔽了我们的双眼。虽然MS替我们做了,我们还是有必要接触它,以在SDK or 其他地方有的放矢。我做了一个球体演示的例子,其界面如下:   左侧两个表面积和体积Edit让使用者从文本的角度精确地观察,我们称其为TextView。右侧为从CStatic派生的CGraphicView,使得人们可直观地观察Sphere.对话窗口CMVCSphereDlg是控制器,来获取用户的键盘输入(输入半径后回车)和在Static上的鼠标点击与拖动(可动态调整球体半径并实时反馈球体变化)而CSphere类是模型,存储了球体半径和计算表面积,计算体积等处理半径数据的操作.   现在让我们详细看看代码,来感受下Model,View,Controller之间如何关联,如何协同工作的。 class CSphere { public: ... .... //更新Graphic-VIEW BOOL UpdateGraphicView(HWND hWnd,const CRect &rect,BOOL bErase); //更新Text-VIEW void UpdateTextView(); //外界Controller的接口:设置球体半径 void SetRadius(float r); private: //球体半径 float m_fRadius; //计算球体表面积 float CalculateArea(float radius); //计算球体体积 float CSphere::CalculateVolumn(float radius); };   这里面 UpdateTextView,UpdateTextView 就是当用户输入新半径或拖动鼠标 Controller 捕获后通知 Model,Model 通知两个View更新显示 。具体代码如下: BOOL CSphere::UpdateGraphicView(HWND hWnd,const CRect &rect,BOOL bErase) { //data format examination if(!::IsWindow(hWnd)||::IsRectEmpty(&rect)) { AfxMessageBox("View is not created by now or rect is empty"); return false; } //get the window pointer from window handle CWnd *pView = CWnd::FromHandle(hWnd); if(pView == NULL) return false; //set graphic view''s radius in order to painting ((CGraphicView*)pView)->SetRadius(m_fRadius); bPaintSphere = true;//set paint tag true //repaint if(!::InvalidateRect(hWnd,&rect,bErase)&& !::UpdateWindow(hWnd)) { AfxMessageBox("UpdateView failed"); return true; } pView = NULL; return false; } void CSphere::UpdateTextView() { CMVCSphereDlg *parent = (CMVCSphereDlg *)AfxGetMainWnd(); CWnd *wnd1 = parent->GetDlgItem(IDC_SURFACE); CWnd *wnd2 = parent->GetDlgItem(IDC_VOLUMN); CString str; str.Format("%.2f平方米",CalculateArea(m_fRadius)); wnd1->SetWindowText(str); str.Empty(); str.Format("%.2f立方米",CalculateVolumn(m_fRadius)); wnd2->SetWindowText(str); } CGraphicView中绘图关键代码如下: void CGraphicView::OnPaint() { ... ..... if(!bPaintSphere) dc.DrawText("球体演示",rect,DT_VCENTER|DT_CENTER|DT_SINGLELINE); else { int r=(int)m_radius;//半径取整 CPoint MiddlePoint = rect.CenterPoint();//以矩形框的中心为球心 int x=MiddlePoint.x; int y=MiddlePoint.y; oldpen = (CPen*)dc.SelectObject(&solid_pen); oldbru = (CBrush*)dc.SelectObject(&brush); dc.Ellipse(x-r,y-r,x+r,y+r); //先画一个圆形 dc.SelectObject(&dash_pen); dc.Arc(x-r/2,y-r,x+r/2,y+r,x,y-r,x,y+r); //再画4个半圆弧 dc.Arc(x-r/2,y-r,x+r/2,y+r,x,y+r,x,y-r); dc.Arc(x-r,y-r/2,x+r,y+r/2,x-r,y,x+r,y); dc.Arc(x-r,y-r/2,x+r,y+r/2,x+r,y,x-r,y); ... ... } } 关于控制器CMVCSphereDlg响应用户输入半径回车核心代码如下: BOOL CMVCSphereDlg::PreTranslateMessage(MSG* pMsg) { UpdateData(); //violation examination if(m_r100) { AfxMessageBox("半径输入范围(0---100)"); return false; } if(pMsg->message == WM_KEYDOWN) if(pMsg->wParam == VK_RETURN)//回车 { CRect rect; m_GraphicView.GetClientRect(rect); m_Sphere.SetRadius(m_r);//把用户输入转换成对Model的操作 m_Sphere.UpdateTextView();//更新View m_Sphere.UpdateGraphicView(m_GraphicView.GetSafeHwnd(),rect,true);//更新View return true; } ... ... } 响应鼠标拖动核心代码如下: void CMVCSphereDlg::OnMouseMove(UINT nFlags, CPoint point) { CRect rect; m_GraphicView.GetClientRect(rect); CPoint middlepoint = rect.CenterPoint(); //if click on the graphic view if(rect.PtInRect(point)&&bIsDragging) { double dbDistance2 = (point.x-middlepoint.x)*(point.x-middlepoint.x)+(point.y-middlepoint.y)*(point.y-middlepoint.y); double dbDistance = sqrt(dbDistance2); if(dbDistance>100.) dbDistance = 100.; m_r = (float)dbDistance; //update radius edit UpdateData(false); m_Sphere.SetRadius(m_r); m_Sphere.UpdateTextView(); m_Sphere.UpdateGraphicView(m_GraphicView.GetSafeHwnd(),rect,true); } ... ... } 该程序功能简单,只是示例性说明采用 MFC 如何实现MVC模型,就当砖引玉了。具体实现参考源代码例子。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值