- Home /
Unity Character Controller messing up.
I'm trying to make a click-to-move system, but it seems like whenever I press somewhere on the map, the character goes to the place, but doesn't stop, yet goes crazy. (Moving around in circles etc.)
If I increase the number in the vector3.Distance, it'll eventually stop going crazy, but the position will be far off.
 // Current selected player
     public GameObject curPlayer;
     CharacterController controller;
 
     public float speed = 5.0f;
     public Vector3 position;
 
     void Start ()
     {
         controller = curPlayer.GetComponent<CharacterController>();
 
         position = curPlayer.transform.position;
     }
 
     void Update()
     {
         if (GameManager.gameRunning) 
         {
             if (Input.GetMouseButtonUp(1))
             {
                 controller = curPlayer.GetComponent<CharacterController>();
 
                 locatePosition();
             }
             moveToPosition();
         }
     }
 
     void locatePosition()
     {
         RaycastHit hit;
         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
 
         if (Physics.Raycast(ray, out hit))
         {
             position = hit.point;
         }
     }
 
     void moveToPosition()
     {
         if (Vector3.Distance(curPlayer.transform.position, position) > 1)
         {
             Quaternion newRotation = Quaternion.LookRotation(position-curPlayer.transform.position, Vector3.forward);
 
             newRotation.x = 0f;
             newRotation.z = 0f;
 
             curPlayer.transform.rotation = Quaternion.Slerp (curPlayer.transform.rotation, newRotation, Time.deltaTime * 10);
             controller.SimpleMove(curPlayer.transform.forward * speed);
         }
     }
The chances of hitting an exact float based Vector3 are pretty slim; floating point inaccuracy and that.
You also kinda need to tell it to stop, I imagine. Like turning off the engine when you've reached the shops :P
as meat5000 already said, you need something like
 if (your_current_position is < 1 meter from the target) {
     stop_the_movement
 }
Checking if the position is exactly your target position is almost impossible. Your player 'goes crazy' because he over-shoots his target, turns around to get to it again, but over-shoots it again. It then does this over and over and over again.
Your answer
 
 
             Follow this Question
Related Questions
Want to move object slowly to where the mouse clicks? 1 Answer
Difference between hit.collider.gameObject vs hit.transform.gameObject 2 Answers
Look at enemy 1 Answer
How to teleport a character to a given position? 2 Answers
Set forward vector of an object to be EXACTLY equal to another vector. 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                