【问题标题】:Need assistance in OpenGL in android在 android 中需要 OpenGL 的帮助
【发布时间】:2012-01-13 14:49:40
【问题描述】:

我创建了 3 个 Java 类。

  1. 具有 glsurfaceview 对象并调用渲染器类的对象。
  2. 这是渲染器类,它调用立方体类。
  3. 这是立方体类。

如果我运行应用程序,那么屏幕会显示一个旋转立方体(在渲染类中进行了旋转),这很好。但我想控制立方体的旋转方向,为此我设置了 2 个按钮。这是我需要帮助的地方,因为我不知道如何让按钮控制立方体的移动。我是 Android 新手,所以如果你能留下一些代码让我检查,那就太好了。

【问题讨论】:

    标签: android button opengl-es surfaceview


    【解决方案1】:

    您的 Activity 类(或扩展 Activity 的类)应如下所示:

    public class stackoverflowTest extends Activity {
    
    GLSurfaceView glSurface;
    MyRenderer myRenderer;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.main);
    
        myRenderer = new MyRenderer(this);        
        //Create an instance of the Renderer with this Activity
    
        glSurface = (GLSurfaceView) findViewById(R.id.graphics_glsurfaceview1);
        //Set our own Renderer and hand the renderer this Activity Context
    
        glSurface.setEGLConfigChooser(true);
    
        glSurface.setRenderer(myRenderer);
        //Set the GLSurface as View to this Activity
    
    
    }
    
    /** 
    * this is the method the button click calls
    */
    public void changeRotationDirection(View v){
    
        myRenderer.changeRotationDirection();
    
    
    }
    
    }
    

    然后在你的渲染器中:

    public class MyRenderer implements Renderer {
    
    private float rotationDirection = 1.0f;
    
    
    public MyRenderer(Context context){
        this.context = context;
    }
    
    public void setRotationDirection(){
    
        if(rotationDirection==1.0f){
            rotationDirection=-1.0f;
        } else {
            rotationDirection=1.0f;
        }
    
    }
    
    @Override
    public void onDrawFrame(GL10 gl) {
            // GL calls
    
            gl.glRotatef(angle, rotateDirection, 0.0f, 0.0f);
    
            // draw cube
            gl.glDrawArrays( etc );
    
        }
    
    }
    

    基本上,您可以在绘制立方体之前使用glRotatef 旋转立方体。对角度参数(第一个)或 x,y,z 量参数使用 -ve vales 以沿相反方向旋转。使用对Renderer 的方法调用与其通信并更新场景。谨慎使用此方法,因为 Renderer 线程和 Main/UI 线程(从中进行按钮调用)可能存在同步问题

    要使按钮调用changeRotationDirection 方法,只需将android:onClick="changeRotationDirection" 添加到XML 布局中(任何视图。不必只是一个按钮视图)。在 XML 布局中声明的任何按钮方法都必须采用 public void [methodname](View [paramname]) 的形式,并且必须位于按下按钮的 Activity 类中

    如需更高级的触摸控制,请按照 Erik 的建议查看并查看 OnTouchListeners

    (注意:如果您使用的是 openGL-ES 2.0 或更高版本(android 2.2+),请使用GLES20.glRotatef()

    【讨论】:

      【解决方案2】:

      您可能想查看 sdk 中的 TouchRotateActivity 示例。如果我没记错的话,它位于 samples/platform/api-demos 文件夹中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多