Search code examples
c#3ddirectxsharpdx

SharpDX: Move an object without manipulating the vertices


i am using SharpDX and trying to move an object in worldspace. As i load an object from web (.obj-file) the received data gets written into a buffer. So i do not have a chance to manipulate it. I know that one can move, rotate and scale object with the help of a matrix. But then again, i only got the vertex- and indexbuffer for the mesh. Is there anything i have overseen to transform a mesh in worldspace?


Solution

  • I do not know enough but I think you need to add a worldViewMatrix for each mesh later have a vector3 called position, a property for your each mesh to pass parameters trough Matrix.Translation(position.x,position.y,position.z). Your buffer is stored in gpu you can not change it directly so you move them with matrices.

    Something like inside mesh class or whatever you use:

    Matrix WorldViewMatrix;
    public Vector3 Position;
    
        public void Render( SharpDX.Direct3D11.Buffer constantBuffer, SharpDX.Direct3D11.Device device, Matrix viewProj )
        {
        WorldViewMatrix =  Matrix.Scaling(Scale) * Matrix.RotationX(Rotation.X) * Matrix.RotationY(Rotation.Y) * Matrix.RotationZ(Rotation.Z) * Matrix.Translation(Position.X, Position.Y, Position.Z) * viewProj;
        WorldViewMatrix.Transpose();
        device.ImmediateContext.UpdateSubresource(ref WorldViewMatrix, constantBuffer);
        //device.ImmediateContext.PixelShader.SetShaderResource(0, textureView);
        device.ImmediateContext.Draw(VerticesCount,0);
        }
    

    Later you will create viewMatrix

    var viewProj = Matrix.Multiply(myMesh.ViewLayer.Camera.getView(), proj); 
    //Whatever your organization is I did it like myMesh.ViewLayer.Camera.getView() for my purpose. I assume you had camera setup already.
    

    Finally ready to move:

    Matrix proj = Matrix.Identity;
    
        RenderLoop.Run(form, () =>{
                var viewProj = Matrix.Multiply(myMesh.ViewLayer.Camera.getView(), proj);
                //...
                    if (IHandler.KeyRight) { myMesh.Position.X += 0.050f; }
                    if (IHandler.KeyLeft)  { myMesh.Position.X -= 0.050f; }
                    if (IHandler.KeyUp)    { myMesh.Position.Z += 0.050f; }
                    if (IHandler.KeyDown)  { myMesh.Position.Z -= 0.050f; }
                    if (IHandler.KeyQ)     { myMesh.Position.Y -= 0.050f; }
                    if (IHandler.KeyE)     { myMesh.Position.Y += 0.050f; }
                //...
                myMesh.Render(contantBuffer, device, viewProj);
        });
    

    My Result here: https://www.youtube.com/watch?v=dn4RdD6tc7g