Reputation: 1590
When creating a door script in Unity, you have to set a pivot point. You make the door being a child of this pivot point. When opening the door, the pivot point gets rotated and the door will rotate relative to it automatically.
I know you can create an empty GameObject in the editor, but I want to do it by code.
[SerializeField]
Vector3 pivotPosition; // the spawn position of the pivot point
Transform pivot;
void Start()
{
pivot= new GameObject().transform; // create the pivot point
pivot.position = pivotPosition; // position the pivot point
transform.SetParent(pivot); // parenting
}
So this works fine, when having a door rotated by (0,0,0) in the inspector.
When rotating the door for example (0,-30,0) the pivot point is not placed correctly when creating it.
How can I create this pivot point correctly, having a correct placement even if the door is rotated by (x,y,z)
Upvotes: 2
Views: 7800
Reputation: 6441
There are multiple possible solutions. Here are the ones I know about, in my order of preference:
Transform.RotateAround()
.rotation * (vector - pivot) + pivot
rotation
= Quaternion
representing your rotation.(vector - pivot)
puts your object at "origin" to apply rotation (same logic as using hierarchy method).+ pivot
= reapplies the offset between the object and the pivot, after the rotation did it's thing.Quaternion
s, the Quaternion
should always be the first operand (don't do this: (vector - pivot) * rotation
).Upvotes: 0
Reputation: 967
You could use Transform.RotateAround
Example
using UnityEngine;
public class RotateAround : MonoBehaviour {
public Transform pivot;
public float degreesPerSecond;
void Update () {
transform.RotateAround(pivot.position, Vector3.up, degreesPerSecond * Time.deltaTime);
}
}
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
Upvotes: 3
Reputation: 443
By doing pivot.position = pivotPosition;
you are placing the pivot at the center of your object.
I see 3 viable options here:
1 - If you are making the model of the door, you could make its center be on the pivot's position also on the ground to help position the door's height.
2 - Use a door prefab with a parent object on the pivot's position. (Could actually use that parent as pivot instead of creating it by script)
3 - If the Door's GameObject center is in its center and you can't change it you can calculate it either manually or using MeshRenderer.bounds.
Upvotes: 1