How to drag 2D Object in Spark AR Studio
This is a patch tutorial to learn how to drag 2D object Spark AR Studio using the Screen Pan Interaction. Screen Pan can tell us the 2D position of our moving touch location. We could use another touch Interaction Patch, but since we want to drag, Screen Pan can help.
- Add a Canvas object to the Scene panel on the left. The Canvas object is a container for laying out 2D objects and making them responsive to the size of the screen.
- Add a Rectangle to the scene as a child (below) the Canvas. This is going to be our drag object. I named it DragObject.
- Hot Tip: adding a Rectangle before the Canvas will automatically create a Canvas.
- Add the DragObject Position property to the Patch Editor by selecting the little arrow next to it’s Position in the Properties panel on the right.
- Device: drag it from the Scene panel on the left side into the Patch Editor to access Device properties like screen size. This will give the Patch Editor access to device specific information.
The Drag 2D Object Patch
Here is what the completed drag 2D object patch looks like.
About This Patch
Objects on the Canvas are positioned in Cartesian coordinate space.
Screen Pan touch location is measured in Screen coordinate space.
In order to accurately drag a 2D object on the Canvas, we need to convert the Screen Pan 2D position to match the Cartesian coordinate of the DragObject. We need information from Device and Screen Pan to achieve this.
Get Screen Size
- Device can tell us the dimensions of the screen specific to the device using the effect.
- Unpack the Screen Size values to view the screen size. If you change the simulator device in Spark AR Studio, you will see these values change.
Get Screen Pan
- Screen Pan has a state, which can be used to trigger a change in the default value set when the effect loads.
- Unpack the Screen Pan 2D position to view where the touch is happening in Screen coordinate space.
Convert Screen Coordinates to Cartesian Coordinates
CartesianX = (ScreenPanX) – (ScreenWidth / 2) / ScreenScale
CartesianY = -(ScreenPanY) + (ScreenHeight / 2) / ScreenScale
If this patch was helpful, please leave a comment or check out other useful patches. Thanks.