0

Using Unity's new input system, I would like to detect a start touch and and end touch. Using these, I'd like to compute the distance and direction for the camera to move, so the camera moves with a "swipe". However, I am having trouble figuring out how to detect these touches in Update().

Pseudocode would be:

private void Update() {

// get start position
// get end position
   MoveCameraOnSwipe()
}

I've figured out what goes in MoveCameraOnSwipe(), or how to move the camera using a target position and direction. The only part I can't figure out is how to use the new input system to capture the start and end values in Update.

I could try to read the values directly, but not sure how that would work:

We could return values from the touch using this method, where Screen Controls is player input:

public Vector2 PrimaryPosition()
    {
        return screenControls.SwipeMap.PrimaryPosition.ReadValue<Vector2>();
    }

Then in Update() - would I do something like:

     screenControls.SwipeMap.PrimaryContact.started += context => StartTouchPrimary(context);
     screenControls.SwipeMap.PrimaryContact.canceled += context => EndTouchPrimary(context);

But this doesn't seem quite complete. Any help would be appreciated.

1 Answers1

0

Register to the events in OnEnable, and unregister from them is OnDisable. This prevents hanging references, which can cause memory leaks (since there is a reference tied to the event still).

On started store the position to a variable startPosition.

screenControls.SwipeMap.PrimaryContact.started += ctx => {
    startPosition = ctx.ReadValue<Vector2>();
}

On canceled store the value to a variable endPosition.

screenControls.SwipeMap.PrimaryContact.canceled += ctx => {
    endPosition = ctx.ReadValue<Vector2>();

    // At this point you want to take a copy of the start and end positions,
    // calculate the distance and direction, and start  the camera move
}

Make sure to take a copy of the start and end positions (notably the start position) before starting the movement. startPosition can be reassigned while the camera movement is taking place (think completing a swipe, and immediately starting a new swipe).

For Update, add a boolean cameraMoving which will indicate if your movement function should be running. The boolean should be set to true when cancel happens and set to false when the movement is complete.

private void Update()
{
    if (cameraMoving)
    {
        MoveCameraOnSwipe();
    }
}

If a new swipe happens while the camera is moving, you can set startPosition to the current camera position to prevent the camera jumping back to the new swipes starting position.

hijinxbassist
  • 3,667
  • 1
  • 18
  • 23