gpt4 book ai didi

javascript - 检测何时触摸另一个 View - 在 React Native 中使用 PanResponder 拖动

转载 作者:数据小太阳 更新时间:2023-10-29 04:52:28 27 4
gpt4 key购买 nike

我有一个纸牌游戏,用户可以在屏幕上拖动纸牌。

如何检测卡片是否已被拖到其他 View 组件上?我的可拖动卡片代码是这样的:

// A draggable card
// drag drop code example used: https://github.com/brentvatne/react-native-animated-demo-tinder
// panresponder docs: https://facebook.github.io/react-native/docs/panresponder.html

class Card extends React.Component {
componentWillMount() {
this.state = {
pan: new Animated.ValueXY(),
enter: new Animated.Value(1),
}

this._panResponder = PanResponder.create({

onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
Animated.spring(this.state.enter, {
toValue: .75,
}).start()

this.state.pan.setOffset({x: this.state.pan.x._value,
y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0});
},

onPanResponderMove: Animated.event([
null, {dx: this.state.pan.x, dy: this.state.pan.y},
]),

onPanResponderRelease: (e, {vx, vy}) => {
// do stuff when card released
}

Animated.spring(this.state.enter, {
toValue: 1,
}).start()

this.state.pan.flattenOffset();
var velocity;

if (vx >= 0) {
velocity = clamp(vx, 3, 5);
} else if (vx < 0) {
velocity = clamp(vx * -1, 3, 5) * -1;
}

Animated.spring(this.state.pan, {
toValue: {x: 0, y: toValue},
friction: 4
}).start()
}
})
}

最佳答案

我不知道这是否是解决问题的最佳方式,但我会得到 onLayout目标 View 的 x、y、宽度和高度...

<View onLayout={({nativeEvent: {layout: {x,y,width,height}}) => { })} />

容器覆盖的坐标就是 (x, x+width) 和 (y, y+height)

onPanResponderGrant获取可拖动的位置:

onPanResponderGrant: (e) => {
this.originX = e.pageX - e.locationX;
this.originY = e.pageY - e.locationY;
}

onPanResponderMove你可以这样做:

onPanResponderMove: (e, gestureState) => {
const currentX0 = this.originX + gestureState.dx
const currentY0 = this.originY + gestureState.dy
}

可拖动现在涵盖了 currentX0currentX0 + width来自 currentY0currentY0 + height ...

您可以使用这些值来检查它是否与目标 View 重叠(x, x+width)(y, y+height)

关于javascript - 检测何时触摸另一个 View - 在 React Native 中使用 PanResponder 拖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33588198/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com