Arrow keys becoming inverted in player movement after coroutine starts.

Hi,

I’ve been trying to make it so that the player is forced to look at an object in the game when the player is close enough. I want the player’s view locked off, looking at the object for 5 seconds, with MouseLook disabled.

I put a gameobject target infront of the object in the game to provide the transform location I want the player to moveTowards and rotate to.

It works, it’s just that after the target is made inactive, to return autonomy to the player, the arrow keys become inverted. The left arrow key makes the character go right, the forwards key makes it go back.

It’s really weird. If anyone knows why this is happening, or can see a better way to do this code, that would be deeply rad.

using UnityEngine;
using System.Collections;

public class TransformTest : MonoBehaviour {

    public Transform player;
    public float playerDistance;
    public float moveSpeed;
    //public Transform target;
    public GameObject target;
    public MouseLook subject;
  

    // Use this for initialization
    void Start () {

        target = GameObject.Find("target");
        gameObject.active = true;
        subject = GameObject.Find("Main Camera").GetComponent<MouseLook>();
   
      

    }

    // Update is called once per frame
    void Update() {

        playerDistance = Vector3.Distance(player.position, target.transform.position);
      
        if (playerDistance < 15f)
        {
          
            subject.transform.rotation = target.transform.rotation;
        
            player.transform.position = Vector3.MoveTowards(player.transform.position, target.transform.position, moveSpeed * Time.deltaTime);

         
                StartCoroutine("NewDir");
            }
        }
   

    IEnumerator NewDir() {
 
        yield return new WaitForSeconds(5.0f);

        {
     
            target = GameObject.Find("target");
            gameObject.active = false;

        }



        }


        }

Are you using the FPSController from the old StandardAssets?
I think it had one separate MouseLook for vertical and horizontal rotation.
If this is your case, directly setting the rotation of one of them may not work and would perhaps be causing the desync of perceived forward direction. Then you would need to set their rotation individually.

One other thing to note is that you start a Coroutine in Update, but you don’t check if that Coroutine is already running, which could cause you to start additional routines unintentionally. Several of the same routines can be running, and if you’re not aware of this, you may run into unexplainable behaviour.

Although personal preference, if your objects are already in the scene and will remain there, it’s usually better to set up the references to other objects via the public fields in the inspector. Then you don’t need to use GameObject.Find()

1 Like

Thanks for your feedback.