You will need to simplify this. First, you are running back and forth because you are translating it farther than the remaining distance. This would be fine, if you adhered to the targetRadius. However, you are not, you are using a second if that says if my current point != to my exact distance, then continue. It never will be.
So, I adjusted your code and simplified where needed:
var speed : float = 1;
var targetRadius = 3;
private var target : Vector3;
private var controlCenter : ControlCenter;
function Start (){
controlCenter = FindObjectOfType(ControlCenter);
animation.Play("idle");
rigidbody.freezeRotation = true;
target = transform.position;
}
function Update () {
target.y = transform.position.y;
// you can control the player
if(controlCenter.isSelected == true){
var hit : RaycastHit;
if (Input.GetButtonDown ("Fire1")){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)){
target = hit.point;
Debug.Log(hit.point);
}
}
}
if (Vector3.Distance(transform.position, target) > targetRadius){
transform.LookAt(target);
transform.Translate(0,0,speed * Time.deltaTime);
animation.Play("run");
}else{
animation.Play("idle");
}
}
OK, you need to do a second ray from the transform.position to transform.forward plus the radius of the character. If it hits, just have it stop. If it doesnt continue it.
You sure do like tabs a lot.
Also, you don’t have to translate zero. if you want it to stop moving, just dont translate it.
var speed : float = 1;
var targetRadius = 3.1;
private var target : Vector3;
private var controlCenter : ControlCenter;
private var coll : Coll;
private var characterRadius : float = 1.0;
function Start (){
controlCenter = FindObjectOfType(ControlCenter);
coll = FindObjectOfType(Coll);
animation.Play("idle");
rigidbody.freezeRotation = true;
target = transform.position;
}
function Update () {
target.y = transform.position.y;
var hit : RaycastHit;
var ray : Ray;
// you can control the player
if(controlCenter.isSelected == true){
if (Input.GetButtonDown ("Fire1")){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)){
target = hit.point;
Debug.Log(hit.point);
}
}
}
if (Vector3.Distance(transform.position, target) > targetRadius){
transform.LookAt(target);
var distance=speed * Time.deltaTime;
ray=Ray(transform.position, transform.forward);
if(!Physics.Raycast(ray, hit, distance + characterRadius)){
transform.Translate(0,0,distance);
animation.Play("run");
} else {
animation.Play("idle");
}
}else{
animation.Play("idle");
}
}