Javascript required
Skip to content Skip to sidebar Skip to footer

Unity Gizmo Draw 2d Circle

Draw 2d Physics Shapes in Unity3D

In this tutorial I will show you how to draw and manipulate basic 2D physics shapes with your cursor using Unity, such equally rectangles, circles and triangles. No additional external dependencies are required (tested with 2017.2, but should besides piece of work with 5.x).

  • Play information technology in your browser
  • GitHub Repository
  • Unity Nugget Store Bundle

Background

Back in 2008, I had loads of fun playing IncrediBots. For the uninitiated, the game is very like to Phun (now Algodoo); the game involved drawing basic physics shapes, placing rotating/sliding joints on them, and controlling motor joints with keyboard input. The game featured several puzzles and a rating system for published contraptions.

Here's a few examples of things that yous could make (Credit: uraniu235):

So let'south do the same thing in Unity! Conveniently, Unity has splendid support for 2nd physics, and so implementing a basic image is fairly simple to do.

At that place are 4 parts to this post:

  1. Drawing 2D polygon meshes
  2. Specifying Points with the Cursor
  3. Calculation 2D Physics
  4. Drawing Multiple Shapes

This tutorial will implement drawing rectangles, circles, and triangles.

Drawing 2D Polygon Meshes

I-shaped polygon

To describe a mesh programmatically, Unity requires an array of its vertices and triangles. Unity allows each vertex to be colored differently, so we volition demonstrate this by feeding our mesh random colors. To display the mesh, nosotros apply it to a GameObject's MeshFilter component.

Below is a script that tin can be added to any empty object to draw the shape in the epitome above.

Specifying vertices is easy, equally we can listing them in an assortment of Vector2south. The vertices2D array defines an I-shape. A small complication is that Unity wants an array of Vector3south, and then we need to convert them. System.Assortment.ConvertAll is handy for this.

To find the triangles in a 2nd polygon's list of points, we can utilize a triangulation algorithm. I copied the well-suited Triangulator.cs grade specified in the Unity3D wiki and dropped it in the project. At that place'due south nothing too fancy here; simply give the object a list of points and it will give dorsum the indices of each triangle.

The adjacent step involves creating an array of colors, i for each vertex. Here they are initialized to random colors with Random.ColorHSV() using Linq syntax.

The last step is to create the mesh from the vertices, triangles, and color data and utilize the mesh to a MeshFilter to describe it. Notation that it is a skilful exercise to call mesh.RecalculateBounds() and mesh.RecalculateNormals() to ensure the mesh behaves as it should.

If nosotros attach the script to an empty GameObject, we should come across an I-shaped polygon with lots of colors (see in a higher place). Cheque out commit ane - depict simple polygon mesh to view the results in Unity.

Specifying Points with the Cursor

To capture input from the mouse and create shapes, nosotros will create a controller that handles this. Its task is to create new shapes if no shapes are being fatigued, update shapes if they require additional input, and set shapes loose if they are complete. To keep things simple, a script volition collect new vertices whenever the left mouse button is released (click + drag is left as an exercise to the reader).

Let's start with rectangles. To draw one, nosotros tin specify its two reverse corner vertices with mouse input.

Drawing Rectangles

To aid with simple operations on lists of vectors, we will create a Util.cs script defining a few handy operations.

Adjacent, create an empty Rectangle prefab and attach a script called DrawRectangle.cs. The rectangle prefab is expected have a MeshFilter to draw its mesh (make certain to add together a fabric to properly display the mesh), and LineRenderer to depict a rectangle outline.

DrawRectangle.cs defines two public functions:

  1. AddVertex(Vector2 vertex) adds a new vertex to its internal list of two vertices and calls UpdateShape.
  2. If two vertices have been added, UpdateShape(Vector2 newVertex) replaces its second vertex with a new one. The four corners are extrapolated from the ii vertices to update the mesh and line renderer. The shape is automatically redrawn by Unity every fourth dimension this function is chosen.

The third function, RectangleMesh(Vector2 v0, Vector2 v1, Color fillColor), serves to generate the rectangle mesh similar to the I-shaped polygon in the previous section.

Ane thing to note is that the rectangle's transform fix at the midpoint (centroid) of the mesh. The mesh's vertices are relative to this center point. This volition brand some future calculations nicer (due east.yard., attaching a box collider). Also note that the script exposes a public FillColor, which fills the generated mesh with the given color.

Draw Algorithm

The bones algorithm for drawing a rectangle is every bit follows.

  1. If the left mouse button is released and no rectangle is beingness updated, create a new rectangle with its ii opposite corner vertices at the current mouse position. Bespeak that the rectangle is beingness updated.
  2. If a rectangle is being updated, update the rectangle's final corner vertex to be at the current mouse position.
  3. If the left mouse button is released and a rectangle is beingness updated, stop updating it.

Below we define new script called DrawController.cs. Its job is to collect mouse input and send mouse coordinates to the currently active rectangle GameObject. In essence, it specifies the draw algorithm above.

The property CurrentShapeToDraw holds the electric current rectangle, and IsDrawingShape is the status that allows vertices to be added to the electric current shape.

Check out commit 2 - describe rectangle to view the results in Unity.

Adding second Physics

From what is implemented, calculation physics to these rectangles is simple. First, attach a Rigidbody2D and a BoxCollider2D to the rectangle prefab. The biggest change is in the DrawRectangle.cs script:

  1. Add together a public SimulatingPhysics property that when set, simulates physics with the Rigidbody2D. Otherwise, the shape is gear up to static then that it stops moving and other shapes may still interact with it.
  2. Update the BoxCollider2D'south bounding box after nosotros update the mesh.

Lastly, the DrawController.cs script sets CurrentShapeToDraw.SimulatingPhysics when the current rectangle is complete and ready to be released.

And voila, nosotros have physics! Only brand sure to add together a static platform to preclude rectangles from falling through the scene. Check out commit 3 - add together rectangle physics to view the results in Unity.

Drawing Multiple Shapes

Past extension, cartoon circles, triangles, and arbitrary polygons should be very like to drawing rectangles: supply some vertices via mouse input, create and update meshes/colliders, and simulate finished shapes. The DrawController's code would largely be unchanged: what we demand are scripts defined for each shape on how their mesh and collider should be drawn.

Just there'southward a small catch: how do nosotros keep runway of all the different types of shapes? I opted to use inheritance as it is a tidy manner of getting a handle on all shapes and update them by their public interface. First, we create an abstract class inheriting from Monobehaviour called DrawShape.cs, which looks like this:

Equally nosotros want to dispense the GameObject properties, we use an abstract form instead of an interface. There may exist some code duplication between shapes, only this format enables shapes to be independent of each other in terms of implementation.

The DrawRectangle.cs script should then be updated to inherit from DrawShape, with some additional override keywords for the appropriate methods/properties.

As we will exist drawing rectangles, circles, and triangles, we should update DrawController.cs with all prefabs that nosotros volition be using and expose them every bit public members for Unity, on for each shape type. To make shape selection easier, we volition create an enum called DrawMode that maps a shape blazon to a prefab so that the requested shape type will exist instantiated upon drawing a new shape. In that location will too be a handy dropdown in the Unity inspector to alter betwixt the shape we want to draw.

Drawing Circles

Unity does non back up creating circle meshes or drawing circles out of the box, and so we volition need to implement our own circle-cartoon algorithm. Fortunately, information technology does non require a large amount of code. The basic thought is to estimate a circumvolve by drawing a regular polygon with enough line segments to be duplicate from a circle. To go along this illusion, the number of segments demand to increase every bit the circle's perimeter increases.

Below is the script for DrawCircle.cs, which inherits from DrawShape. Nigh of the code is identical to DrawRectangle.cs. Here we utilize a CircleCollider2D instead of a BoxCollider2D. The biggest difference is in the CircleMesh(Vector2 v0, Vector2 v1, Color fillColor) method.

We can create a manually tuned a linear office called numSegments which increases proportionally to the radius. For each segment, we evenly space Vector2 points effectually the circumvolve using cosine and sine functions. And then the rest is but a echo of what nosotros accept seen before in DrawRectangle.

Check out commit 4 - draw circle and add physics to view the results in Unity.

Drawing Triangles

With triangles, just change the collider type to PolygonCollider2D and we are halfway there. We can create a triangle mesh directly from the list of vertices specified by the cursor.

Tin you gauge how to draw capricious concave polygons? Hint: redefine the condition for when the shape is finished. Check out commit five - draw triangle and add physics to view the results in Unity.

Conclusion

Congratulations on making it this far! As a reward, hither's an easter egg: press the spacebar when your cursor is near some shapes.

I hope you enjoyed the tutorial and accept a newfound appreciation for Unity's simple physics interface. And if anyone wants to collaborate with me on creating a full featured game out of this, contact me.

mccraesonvirsene.blogspot.com

Source: https://hyperparticle.com/2d-physics-shapes/