#Setting transform.rotation also causes the object to move for some reason

1 messages · Page 1 of 1 (latest)

balmy steeple
#

I'm trying to get an object to look towards me when I enter a certain radius but the code I wrote makes it move too for some reaosn

#

Here is the entire script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectionTurn : MonoBehaviour
{
    [SerializeField] private float detectionRadius = 2f;
    [SerializeField] private float rotationSpeed = 1f;
    MoveCamera moveCamera;
    SphereCollider sphereCollider;
    

    private void Start()
    {
        moveCamera = FindObjectOfType<MoveCamera>();
        sphereCollider = GetComponent<SphereCollider>();
    }

    private void Update()
    {
        sphereCollider.radius = detectionRadius;
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            StartCoroutine(TurnTowardsPlayer());
            print("Player is detected");
        }
    }

    IEnumerator TurnTowardsPlayer()
    {
        Transform cameraTransform = moveCamera.gameObject.transform;

        while (true)
        {
            Vector3 objectToPlayeDir = (cameraTransform.position - transform.position).normalized;

            Vector3 newDirection = Vector3.RotateTowards(transform.forward, objectToPlayeDir, rotationSpeed * Time.deltaTime, 0.0f);

            transform.rotation = Quaternion.LookRotation(newDirection);

            yield return null;
        }
    }

}
fiery beacon
#

Btw from what I see its highly likely you will end up multiple of those coroutines running at the same time which will not be good for the performance

balmy steeple
balmy steeple
#

Also stop corotuine for some reason didn't work on them they still followed me

elder axle
#

To use StopCoroutine() I believe you would have to first store the coroutine when starting it

IEnumerator myCoroutine; //Field on top of the script

    private void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            myCoroutine = StartCoroutine(TurnTowardsPlayer());
        }
    }```
#

And then pass in the coroutine reference into StopCoroutine()
StopCoroutine(myCoroutine);

#

Although i have no clue whether you should do this for your specific case, its still good to know you can stop coroutines this way