0

How do you rotate and translate at the same time? In the sample below I was expecting the square to move to right and rotate about its own axis maintaining the same central y axis. If you can imagine a wheel travelling along a road

Instead, it flys off wildly

Any help would be appreciated

import React, { Component } from "react";
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Animated
} from "react-native";

class App extends Component {
  
  componentWillMount () {
    this._animatedValue = new Animated.Value(0);
  }
  componentDidMount () {
    Animated.timing(this._animatedValue, {
        toValue: 100,
        duration: 3000
    }).start(); 
  }
  
  render () {
    
    const interpolatedRotateAnimation = this._animatedValue.interpolate({
        inputRange: [0, 100],
      outputRange: ['0deg', '360deg']
    });

     const interpolatedRotateX = this._animatedValue.interpolate({
        inputRange: [0, 100],
      outputRange: [0, 200]
    });
    
    return (
      <View style={styles.container}>
       <Animated.View 
            style={[styles.box, {transform: [
            {rotate: interpolatedRotateAnimation},
                        {translateX:interpolatedRotateX}

            ]}
            ]}
        />
      </View>
    );
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  box: {
    backgroundColor: 'red',
    position: 'absolute',
    top: 100,
    left: 100,
    width: 100,
    height: 100
  }
});

export default App
0hio
  • 63
  • 5

2 Answers2

1

What I was missing was that the axis was the center of the object. The translate is relative to axis of the own object which is changing due to the rotation.

Translate x/y is not simply moving the object relative to the screen but relative to its own axis.

0hio
  • 63
  • 5
0

@Ohio has it alright, but let me rephrase for the sake of understanding.

CCS transformations are applied one after another, based on the transform-origin property, which is by default the center of the element. If you want to rotate an element over a ray, you need to rotate first to apply the desired angle, and then translate to move the element to the desired ray distance. Doing the translation first, you would apply the rotation based on the new transform-origin value, which is the center of the new position. As for how to do this in React-Native, as mentioned in the Transforms documentation:

transform accepts an array of transformation objects or space-separated string values.

So rotate and translate would look like this:

const styles = StyleSheet.create({
  someElement: {
    transform: [
      rotate: "90deg",
      translateX: 50,
    },
  },
});
theFreedomBanana
  • 2,462
  • 2
  • 22
  • 29