Put 3D objects in xna

I am new to xna development and want to place cubes from Primitives3D sample , passing the position vector to the constructor. Unfortunately, this does not work. Instead, it just spins around.

This is how I changed the code of the cubeprimitive class:

public class CubePrimitive : GeometricPrimitive { public Vector3 position; /// <summary> /// Constructs a new cube primitive, using default settings. /// </summary> public CubePrimitive(GraphicsDevice graphicsDevice) : this(graphicsDevice, 1, new Vector3(-3,0,0)) { } /// <summary> /// Constructs a new cube primitive, with the specified size. /// </summary> public CubePrimitive(GraphicsDevice graphicsDevice, float size, Vector3 posi) { this.position = posi; // A cube has six faces, each one pointing in a different direction. Vector3[] normals = { new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, -1, 0), }; // Create each face in turn. foreach (Vector3 normal in normals) { // Get two vectors perpendicular to the face normal and to each other. Vector3 side1 = new Vector3(normal.Y, normal.Z, normal.X); Vector3 side2 = Vector3.Cross(normal, side1); // Six indices (two triangles) per face. AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 1); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 3); // Four vertices per face. AddVertex(posi+(normal - side1 - side2) * size / 2, normal); AddVertex(posi + (normal - side1 + side2) * size / 2, normal); AddVertex(posi + (normal + side1 + side2) * size / 2, normal); AddVertex(posi + (normal + side1 - side2) * size / 2, normal); } InitializePrimitive(graphicsDevice); } } 

Could you show me how to change it correctly? .. thanks in advance :)

0
primitive xna 3d cube
source share
1 answer

Traditionally, what you do when you want to move the model around, instead of changing each of the vertices of the model, you change the World matrix.

Find this line in Primitives3DGame.cs:

 Matrix world = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll); 

And change it to something like this:

 Matrix world = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll) * Matrix.CreateTranslation(-3, 0, 0); 

(And, of course, delete the change you made as indicated in your question.)

As far as I can tell, your code really works. But perhaps you expected the cube to rotate, but stay in the same place (which is what the code above does). In fact, you are doing the same thing as:

 Matrix world = Matrix.CreateTranslation(-3, 0, 0) * Matrix.CreateFromYawPitchRoll(yaw, pitch, roll); 

Pay attention to the reverse order - first you translate your model, and then rotate around the origin.

+1
source share

All Articles