How to change Player rotation towards nearest other Player?
HelloI, I want the player to turn to the nearest other Player in the Photon Network, also with a turning Time, when pressing a Key.
I already have the script for turning towards an Object:
_direction = (target.position - player.transform.position).normalized;
_direction2 = Quaternion.LookRotation (_direction);
player.transform.rotation = Quaternion.Slerp (transform.rotation, _direction2, Time.deltaTime * RotationSpeed);
But how can I set the target to be the nearest Player in the Photon Network?
Thank you for you time and help!
Hi,
well I guess this is independent from networking logic and more related to your game logic. For your local player you need to compare his distance to each other character and make the character with the shortest distance his 'look at' target.
Can you tell me how to look for distances? And how can I get the GameObjects if they spawn in GameTime?
You can use FindObjectOfType<PhotonView>()
to get all game object which have a PhotonView component attached to them. Since those game objects also might be non-player objects you want to filter them additionally for example by using their tag attribute or something other that is unique to the character objects. When having all player objects you can use Vector3.Distance(Vector3 a, Vector3 b)
to get the distance between your character and each other. While comparing distances, store the game object with the shortest distance locally in order to set the look-at target on that game object.
$$anonymous$$aybe some code will explain this better:
List<GameObject> players = new List<GameObject>();
foreach (PhotonView pView in FindObjectsOfType<PhotonView>())
{
if (pView.is$$anonymous$$ine)
{
continue;
}
if (pView.tag == "Player")
{
players.Add(pView.gameObject);
}
}
GameObject nearest = null;
float distance = float.$$anonymous$$axValue;
foreach (GameObject go in players)
{
float d = Vector3.Distance(transform.position, go.transform.position);
if (d < distance)
{
nearest = go;
}
}
transform.LookAt(nearest.transform);
Your answer
![](https://koobas.hobune.stream/wayback/20220612114322im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotation sync over network best practices (especially; direction) 0 Answers
UNET player and child rotation 0 Answers
Players won't spawn with Photon Unity Network 1 Answer
Photon Bolt: is it a viable solution for a game with a high cheating potential? 1 Answer
My Photon Variable is only owned from MasterClient 0 Answers