#Setting transform.rotation also causes the object to move for some reason
1 messages · Page 1 of 1 (latest)
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;
}
}
}
Im quite confident that this code will not actually move the object origin. Could the origin of the object be somewhere you dont expect it to be?
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
Yes you're right, the cameraTransform was the one causing the issue, I replaced it with the actual location of the player
How would I prevent that?
Also stop corotuine for some reason didn't work on them they still followed me
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