Goibon
Goibon

Reputation: 251

How do I center a mesh on a GameObject?

I have a 2D game where the users can create cars by clicking on the screen to add vertices and then drag these around as they see fit. These vertices are then used to draw a mesh. Users can also add wheels to the vertices (1 per vertex).

In the game there is also an option to have the computer generate a random car, which it does by creating eight vertices at random points inside of a unit circle.

These cars are stored and it is possible for the user to load them and re-use them. The two pictures below show a square button with a computer generated car (The green one with red wheels) which sits inside of the square as intended, and a user generated car (The white one with pink wheels) which sits outside of the square.

I know that this is because the mesh of the computer generated one draws triangles from Vector3.zero which is the center of the object, while the user created one only triangles between the vertices, which aren't necessarily placed around the center of the object (As in this example where they are all placed above and to the right of the center).

How would I go about centering the mesh of the user created car?

I could perhaps calculate the center of the mesh and then subtract that from the position of all the vertices. Or I could subtract that position from the position of the GameObject that holds the mesh when presenting it in the gui. Or are there better alternative solutions?

Object that sits inside of the square Object that does not sit inside of the square

Upvotes: 3

Views: 7515

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8193

Using Mesh.Bounds

Transform car;
Bounds carBounds = car.GetComponent<MeshFilter>().mesh.bounds;
Vector3 whereYouWantMe;
Vector3 offset = car.transform.position - car.transform.TransformPoint(carBounds.center);
car.transform.position = whereYouWantMe + offset;

This will also give you access to a bunch of cool fields like center min max and size

Upvotes: 4

Related Questions