I am working on a click-to-move character controller. I’m trying to learn the concepts behind it. So far, everything I have works perfectly, save for one thing. In my scene, I have three cube gameObjects on the scene. One Cube has my script connected to it, the other two are there just as obstacles.
The problem I have is, at some times, if my cube I’m controlling collides with another cube, when it finally gets around it, it at times continues travelling forever.
Please forgive me for not knowing how to format the code to highlight syntax and such.
Here is my code I have:
var speed : int = 3;
var targetPosition : Vector3;
var travelDistance : float = 0.0;
var curSpeed : float;
var defaultSpeed : int = 3;
function Start () {
targetPosition = transform.position;
}
@script RequireComponent(CharacterController)
function Update () {
var character : CharacterController = GetComponent("CharacterController");
travelDistance = Vector3.Distance(transform.position, targetPosition);
if(travelDistance < .75){
speed = 0;
}
else{
speed = defaultSpeed;
}
//On Mouse left Click
if(Input.GetMouseButton(0)){
//Create a plane for the RayCast to hit
var playerPlane : Plane = new Plane(Vector3.up, transform.position);
var myRay : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//variable for Raycast hit distance
var hitDist : float = 0.0;
//check if the Raycast hits the plane
if(playerPlane.Raycast(myRay, hitDist)){
//create the target Vector where the plane hit
targetPosition = myRay.GetPoint(hitDist);
transform.LookAt(targetPosition);
}
}
if(travelDistance > .75){
curSpeed = speed * Time.deltaTime;
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
character.Move(forward * curSpeed);
}
Debug.Log(travelDistance);
}
I don’t know why it’s doing that. If anyone can help me understand why sometimes the cube will just travel forever after colliding with another, I’d really appreciate it.