我想在 x 和 y 轴上移动一个球,但动画不是柔和的,运动是颤抖的,如果我移动得更快,它不会精确地对角线移动,但是做一个角度,我怎么能用柔和的方式移动球?以下是示例:
https://snack.expo.io/HJvm5WI5N
代码是它:
import React from 'react';
import {Animated, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props)
this.ball = new Animated.ValueXY({x: 30, y: 30})
}
moveBall = () => {
Animated.timing(this.ball, {
toValue: {x: 250, y: 350},
duration: 2000
}).start()
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.moveBall}>
<Animated.View style={[styles.ball, this.ball.getLayout()]}>
<Text style={styles.text}>+</Text>
</Animated.View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
ball: {
width: 60,
height: 60,
borderRadius: 30,
backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontWeight: 'bold',
color: 'white',
fontSize: 32
}
});
您可以使用 useNativeDriver 获得更好的性能。将其与 translateX 和 translateY 一起使用。因为不能将useNativeDriver
与样式的左右属性一起使用。
export default class App extends React.Component {
constructor(props) {
super(props);
this.ball = new Animated.Value(0);
}
moveBall = () => {
Animated.timing(this.ball, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
}).start();
};
render() {
const xVal = this.ball.interpolate({
inputRange: [0, 1],
outputRange: [0, 250],
});
const yVal = this.ball.interpolate({
inputRange: [0, 1],
outputRange: [0, 350],
});
const animStyle = {
transform: [
{
translateY: yVal,
translateX: xVal,
},
],
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.moveBall}>
<Animated.View style={[styles.ball, animStyle]}>
<Text style={styles.text}>+</Text>
</Animated.View>
</TouchableOpacity>
</View>
);
}
}
更新带钩
const App = () => {
const ballAnimatedValue = useRef(new Animated.Value(0)).current;
const moveBall = () => {
Animated.timing(ballAnimatedValue, {
toValue: 1,
duration: 1000,
useNativeDriver: true,
}).start();
};
const xVal = ballAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 250],
});
const yVal = ballAnimatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 350],
});
const animStyle = {
transform: [
{
translateY: yVal,
translateX: xVal,
},
],
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={moveBall}>
<Animated.View style={[styles.ball, animStyle]}>
<Text style={styles.text}>+</Text>
</Animated.View>
</TouchableOpacity>
</View>
);
};