Click-To-Move Script: Character Moves to 0,0 when game starts.

Hey guys. I’m brand new to Unity. I’m having some issue with a Click-to-Move script I’m trying to implement. This isn’t my code, and I wish I could remember the name of the fellow who posted it. Anyway, this script works perfect for me, so long as the object it’s attached to is at point (0,0,0). If I move the object anywhere else on the scene, it immediately starts moving to 0,0,0 from the start. For the life of me, I can’t figure out how to prevent this.

Here is the code:

var smooth:int;
var running:boolean = false;

private var targetPosition:Vector3;

var speed:float = 1.25;
var tempSpeed:float = speed;
var punchSpeed:int = 1;

function Update () {

if(Input.GetKey(KeyCode.LeftShift)){
	speed = 3;
	running = true;
}
else{
	speed = tempSpeed;
	running = false;
}

if(Input.GetKeyDown(KeyCode.Mouse1)){
	var playerPlane = new Plane(Vector3.up, transform.position);
	var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	var hitdist = 0.0;
	
	
	if(playerPlane.Raycast(ray,hitdist)){
		var targetPoint = ray.GetPoint(hitdist);
		targetPosition = ray.GetPoint(hitdist);
		var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
		transform.rotation =targetRotation;
		
	}
	}

var dir:Vector3 = targetPosition - transform.position;
var dist:float = dir.magnitude;
var move:float = speed * Time.deltaTime;
if(dist > move){
	transform.position += dir.normalized * move;
}
else{
		transform.position = targetPosition;
	}
	if (dist > 0){
		if (running){
			animation.CrossFade("run");
		}
		else{
			animation.CrossFade("walk");
		}
	}
	else{
		animation.CrossFade("idle");
}

transform.position += (targetPosition - transform.position).normalized * speed * Time.deltaTime;
}

Please format your code

1 Answer

1

your object is animated, and the positional animation is overriding your movements

make it the child of a controller object, and move the controller instead