Book Image

Extending Unity with Editor Scripting

Book Image

Extending Unity with Editor Scripting

Overview of this book

Table of Contents (18 chapters)
Extending Unity with Editor Scripting
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Implementing the snap to grid behaviour


To create our first level in Chapter 1, Getting Started with Editor Scripting, we used a hot key to snap the level piece prefabs between them. Here, we will do the same, but instead of using the hot key, the level piece prefabs are going to snap to the grid automatically.

Here, we will assume that the Level game object position and rotation is always (0,0,0) and the scale is (1,1,1). Also, the 2D mode is selected by default.

Later, we will work on how keep this configuration by default. Based on the grid we created, we need to implement a few things to achieve our goal:

  • A way to convert 3D coordinates to grid coordinates and vice versa

  • A way to know when these coordinates are outside the boundaries of the grid

Inside the Level class, add the following methods in the Level.cs script:

public Vector3 WorldToGridCoordinates(Vector3 point) {
  Vector3 gridPoint = new Vector3(
  (int)((point.x - transform.position.x) / GridSize) ,
  (int)((point.y - transform...