- Home /
Rotation follow translation
Hi guys
I would like to make an object that rotates on the y axis based on the translation (not rotation) of another object on the x axis.
Something can help me?
Do you mean based on the position or translation of the other object?
Can you show a video or animation of what you're talking about?
Answer by DCordoba · Jan 13, 2019 at 10:00 AM
well after remembering a bit of math, here we go; Iam not sure if diff
get the correct distance, the rest is geometry and the transform.Rotate
function:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicTrack : MonoBehaviour {
public Transform TargetObject; //set it on inspector
public float Angle = Mathf.PI ;//proportional rotation of the second object, default is the same angular translation at diameter 1, multiply by 2 radius to change angular rotation
float StartPoint = 0;
float diff; //reusable variable, distance from current x position to previous
void Start () {
StartPoint = TargetObject.position.x;
}
// FixedUpdate is use by physics
void FixedUpdate () {
//this if really not work with floats, use a aproximate comparision like Mathf.Abs(Mathf.Abs(StartPoint)-Mathf.Abs(TargetObject.x))<0.01f
if (StartPoint != TargetObject.position.x) {
//PI*radius*2 is the distance that a wheel do on a single rotation
diff = TargetObject.position.x-StartPoint;
transform.Rotate (Vector3.up, (360/Angle)*diff);
StartPoint = TargetObject.position.x;
}
}
}
of course the script will be attached to the object that rotate, the TargetObject
is the object moving along the x.
Edited @mustang4484 eliminating the last Mathf.Abs
u have a unclamped rotation at two directions, to do inverse clockwise replace transform.Rotate (Vector3.up, (360/Angle)*diff);
with transform.Rotate (-Vector3.up, (360/Angle)*diff);
(note the minus...)
Answer by mustang4484 · Jan 13, 2019 at 11:13 AM
Thank you all, I explained myself badly. I would like that when my Object P move on the right (B) my arrow turn to (B) with degree proportional to start position-b.
It's a similar to @DCordoba but with the inverse clockwise if the player go to -x.
Thank you
Answer by Magso · Jan 13, 2019 at 12:03 PM
If you have a variable for the rotation then you can do something like this,
float currentRotation, timesDifference, maxAmount;
void Update(){
transform.eulerAngles.y = currentRotation;
other.transform.position.x = currentRotation * timesDifference;
currentRotation = Mathf.Clamp(currentRotation, -maxAmount, maxAmount)
}
edit: I've just noticed A and B are going in opposite directions.
other.transform.position.x = -currentRotation * timesDifference;