Home > Software design >  How to tilt an object depending on the direction of the player on a spherical map
How to tilt an object depending on the direction of the player on a spherical map

Time:08-31

How do I correctly calculate the rotation angle so that the object dodges the player? It means that whichever side the player comes from, the object must turn away from the player depending on its direction. I want the effect like in the video but without Joint, only rotation angle: enter image description here

CodePudding user response:

If you're on a sphere you need to use the normal of the ground as the up direction. Since you've probably initially rotated the tree the right way up, you could do the following:

[SerializeField] Transform player;
[SerializeField] float effectMaxDistance=1;
[SerializeField] float maxAngle=50;

Quaternion initialRotation;
Vector3 initialUp;

void Start(){
  initialRotation = transfrom.rotation;
  initialUp = transfrom.up;
}

void Update(){
  Vector3 dir = player.position - transform.position;
  Vector3 axis = Vector3.Cross(dir, initialUp);
  float angle = (1-(Mathf.Clamp(dir.magnitude, 0 effectMaxDistance) / effectMaxDistance)) * maxAngle;
  transform.rotation = initialRotation * Quaternion.AngleAxis(angle, axis);
}
  • Related