如何在react-native中检测组件碰撞?

时间:2019-03-21 00:45:22

标签: javascript react-native

首先,我是刚开始问堆栈溢出问题的人,所以对我们轻松一点。 我正在尝试找出如何检测组件碰撞的方法。即,包含按钮圆形组件的可拖动组件。可悲的是,关于此的在线信息似乎为零。我认为可拖动组件可能能够处理某种半径跟踪,这是在用户将手指从屏幕上移开时计算出来的,但是硬跟踪半径似乎会占用大量资源。伙计们,我真的需要一些想法。相关代码如下。

Draggable.js

import React, { Component } from "react";
import {
  PanResponder,
  Animated,
} from "react-native";

import CircleButton from 'react-native-circle-button';

export default class Draggable extends Component {

  constructor(props) {
    super(props);

    this.state = {
      pan: new Animated.ValueXY(),
      scale: new Animated.Value(1),
    };
  }



  //Function to handle animations and button pressing of bubbles.
  componentWillMount() {
    let finalx = 0;
    let finaly = 0;

    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
      onMoveShouldSetPanResponder: (evt, gestureState) => {
        return gestureState.dx <= finalx && gestureState.dy <= finaly;
      },

      onMoveShouldSetPanResponderCapture: (evt, gestureState) => {
        return gestureState.dx <= finalx && gestureState.dy <= finaly;
      },

      onPanResponderGrant: (e, gestureState) => {
        this.state.pan.setValue({x: 0, y: 0});
        this.finalx = gestureState.dx;
        this.finaly = gestureState.dy;
        Animated.spring(
          this.state.scale,
          { toValue: 1.1, friction: 3 }
        ).start();
      },

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

      onPanResponderRelease: (e, {vx, vy}) => {
        this.state.pan.flattenOffset(); 
        Animated.spring(
          this.state.pan,
          { toValue: {x:0, y:0}},

          this.state.scale,
          { toValue: 1, friction: 3 }
        ).start();
      }
    });
  }

  render() {
    let { pan } = this.state;

    let rotate = '0deg';

    let [translateX, translateY] = [pan.x, pan.y];

    let moveableStyle = {transform: [{translateX}, {translateY}, {rotate}]};
    const panStyle = {
      transform: this.state.pan.getTranslateTransform()
    }
    return (
      <Animated.View
        {...this._panResponder.panHandlers}
        style={[moveableStyle, panStyle]}>
          <CircleButton />
      </Animated.View>
    );
  }
}

Homepage.js

<View style={styles.middleContainer}>
    { this.state.bubbles.map((item, key)=>(
        <Draggable key={key}> { item }</Draggable>)
    )}
</View>

0 个答案:

没有答案