Draggable object reset to original position using panhandler in React Native

25 Views Asked by At

I'm trying to create a simple drag&drop component to later turn it into a draggable picture. I want to be able to move a picture freely in a certain space (in this instance in the area, where gesture.moveY is smaller than 800) and for it to reset to its original position (outside of this box), when the picture is dragged out of the gesture.moveY area. Right now however when the object gets dragged into the "movable" space its resting placed is used as a x:0, y:0 point for future movements, and so, when it leaves the movable area it gets back into it instead of the original "spawnpoint".

My draggable file:

import { StyleSheet, Text, SafeAreaView, StatusBar, View, TextInput, Image, Button, PanResponder, Animated } from 'react-native';
import { Link } from 'expo-router'
import { observer } from 'mobx-react';
import { useStore } from '../mobx/store';
import React, { Component, useRef, useState } from 'react';

const Draggable = () => {
    const pan = useRef(new Animated.ValueXY()).current;
    this.state = {
        showDraggable: true,
        dropAreaValues: null,
        pan: new Animated.ValueXY(),
        opacity: new Animated.Value(1)
    };

    const panResponder = useRef(
        PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onPanResponderMove: Animated.event([null, { dx: pan.x, dy: pan.y }]),
            onPanResponderRelease: () => {
                pan.setOffset(offset, {x: x, y: y});
            },
            onPanResponderRelease: (e, gesture) => {
                if (gesture.moveY < 800) {
                    pan.extractOffset();
                    
                } else {
                    Animated.spring(pan, {
                    toValue: { x: 0, y: 0 },
                    friction: 5
                }).start();
                } 
            }
        })
    ).current;


    const panStyle = {
        transform: pan.getTranslateTransform(),
    };

    return <Animated.View {...panResponder.panHandlers} style={[panStyle, styles.circle]} />;
};

export default Draggable;
let CIRCLE_RADIUS = 30;
const styles = StyleSheet.create({
    circle: {
        backgroundColor: "skyblue",
        width: CIRCLE_RADIUS * 2,
        height: CIRCLE_RADIUS * 2,
        borderRadius: CIRCLE_RADIUS
    }
});

I tried using ChatGPT, but I thik I couldn't explain the problem to it properly, and so it kept offering me nothing useful.

0

There are 0 best solutions below