- Home /
Question by
kamran_f · Aug 31, 2018 at 05:48 PM ·
rotationlookrotationalign two objects
Align Key to Keyhole??
Thank you in advanced for your help; i have a key and key hole on a object with keyhole, i can rotate keyhole object in every rotation in world to look every part of it and when i push some button the key will move and align to the key hole entrance, i managed to move the key into the proper position but the key rotation is not right and i couldn't find any solution, i'm so new to unity and coding.
key : red box (0.05,0.2,2) is my key
keyhole : the empty object with icon child to the box is supposed to be my key hole,

whet i run my code key goes to the keyhole properly bu as you can see the rotation is not right,

and this is my code
public Transform target;
public float speed = 3;
private Vector3 direction;
private Quaternion lookRotation;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float step = speed * Time.deltaTime;
// key scale is 0.05,0.2,2 so i add a 1 unit distance from key center to hole
Vector3 distance = new Vector3(0, 1, 0);
transform.position = Vector3.MoveTowards(transform.position, target.position + target.rotation * distance, step);
//find the vector pointing from our position to the target
direction = (target.position - transform.position).normalized;
//create the rotation we need to be in to look at the target
lookRotation = Quaternion.LookRotation(direction, transform.up);
//rotate us over time according to speed until we are in the required rotation
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, 0.3f);
}
Comment
Your answer