Draggable power sources

The power sources are prefabs. There are two of them already instantiated in the scene. In order to make them draggable, we simply have to use the UIDragObject component.

UICamera

First things first; we need GameCamera to have the UICamera component attached to it in order to trigger events on 3D world objects like the ground or the power sources. To get the required results, perform the following steps:

  1. Select the GameCamera GameObject.
  2. Click on the Add Component button in the Inspector view.
  3. Type in uicam to search for components with that name.
  4. Select NGUI Event System (UICamera), and hit Enter or click on it.
  5. Set the newly attached UICamera component's Event Type to 3D World.
  6. Make sure Event Mask is set to Everything and not just 2DUI.

OK. The GameCamera GameObject is now ready to trigger events on 3D objects. We can now make our power sources draggable objects.

UIDragObject

Let's use the UIDragObject component to drag our power sources in the 3D world:

  1. In the Project view, select Assets/Resources/Prefabs/PowerSource.
  2. Click on the Add Component button in the Inspector view.
  3. Type in obj to search for components with that name.
  4. Select Drag Object, and hit Enter or click on it with your mouse.

For the newly added UIDrag Object component on our PowerSource prefab:

  1. Drag Resources/Prefabs/PowerSource (itself) in the Target field.
  2. Set the Movement constraints to {1, 0, 1} to limit movement to the X and Z axes.
  3. Set Drag Effect to None to make the drag more precise and responsive.

OK. The Drag Object component is configured. But, as we have learned in previous chapters, NGUI components using events need Box Collider attached to them.

Box Collider

For the UIDragObject component to work, it needs to have Box Collider attached to it in order to receive UICamera events:

  1. In the Project view, select Resources/Prefabs/PowerSource.
  2. Click on the Add Component button in the Inspector view.
  3. Type in box with your keyboard.
  4. Select Box Collider and hit Enter or click on it with your mouse.
  5. Set Size to {4, 4, 4}.

OK, now that we have the Box Collider and the UIDragObject components, hit Unity's play button. You can now drag-and-drop both our power sources on the scene!

Now, let's now see how we can make the player move to a clicked position on the ground or an interactive element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.95.245