- Home /
if x, make gameobject face player C#
Hello,
I guess this is pretty easy but I'm having a bit of a moment here, help would be much appreciated. I'm trying to make a GameObject obj smoothly orient to face the player when the player leaves its field of vision. So far I have this
void Update()
{
relativePos = player.position - obj.position;
relativePos.y = 0f;
float angleToPlayer = Vector3.Angle(relativePos, transform.forward);
Debug.Log(angleToPlayer);
if (angleToPlayer <= 60 || angleToPlayer >= 120) {
rotateTowards();
}
}
private void rotateTowards() {
newRotation = Quaternion.LookRotation(relativePos);
maxDegreesPerSecond = -90f; // This is your max speed for rotation in degrees/sec
maxDegreesDelta = maxDegreesPerSecond * Time.deltaTime;
obj.transform.rotation = Quaternion.RotateTowards(transform.rotation,
newRotation,
maxDegreesDelta);
}
which makes the object rotate when the player leaves its field of vision, but only until the if condition isn't met anymore, not until the obj faces the player. it stops at an angle.
If anyone could point me into the right direction how to execute the code in the if-function until the angleToPlayer is exactly 90f/how to style the if-condition to do what I want/how to complete my objective with a completely different approach, that would be awesome!
I have a hunch that this might be possible with a coroutine, but I have trouble understanding enough of the documentation to write one for this. Maybe someone could point me to a tutorial that covers this?
Answer by Captain_Pineapple · Aug 30, 2019 at 09:53 AM
Hey there,
simply introduce a flag indicating your current status. So when your condition with < 60 or > 120 is met, set a rotateNow=true
instead of calling rotateTowards
. Then you can add a statement checking if a endcondition is met. Perhaps something like
if(Mathf.Abs(angleToPlayer-90) < 5)
rotateNow = false;
Then you only need a check for your flag:
if(rotateNow)
rotateTowards();
This in general should work for you. You could also think about using a soluting using a coroutine.
Your answer
![](https://koobas.hobune.stream/wayback/20220612211438im_/https://answers.unity.com/themes/thub/images/avi.jpg)