- Home /
problem with mouseclicke movement
I have a code which I also got from the internet. Here is the code:
var smooth:int; // Determines how quickly object moves towards position
private var targetPosition:Vector3;
function Update () { if(Input.GetKeyDown(KeyCode.Mouse0)) { 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;
}
}
transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * smooth);
}
the problem with this code is that when I click to one place. my character is only facing to the place where I clicked and does not move there. do you know whats missing in this program? and also how will I be able to put the animation walk that after the character moved to the position it wil return to idle animation.. thanks
Answer by aldonaletto · Jan 20, 2012 at 05:03 PM
The only weird thing in your code is smooth being an int - it should be a float. But as far as I know, int float* results in a float, thus this should not kill the movement. Declare smooth as float and assign a reasonable value (5 takes about 1 second).
Another suggestion: the movement above will start fast and slow down near to the destination. If you want a constant speed, use Vector3.MoveTowards:
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
Where speed is in meters per second. As occurs with Lerp, the object will never pass the targetPosition.
ok thanks.. but what about the smooth thing? how should i put a value? is it something like this ? var smooth:float = 2; ? thanks
yes @berting01
var smooth : float = 2 ;
or var smooth : float = 23.0434 ;
... or whatever so long as its a numeric value ;
Don't forget to mark aldo's answer as the accepted if it helped you out.
one more thing... Where should i put my animation named walk and play here. I am able to put the animation.play("walk") but the problem is the moment i clicked. it wont stop. @lo0Nuhti$$anonymous$$
the animation walk will play when moving to the clicked direction and the animation idle will play after reaching the position. how do i do that here
Your answer
Follow this Question
Related Questions
Using Raycast to detect what's hit and if it's tagged 2 Answers
Object Movement via Mouse Click? 3 Answers
click to move workig script!! but pls help with rotation!! :( 1 Answer
Camera/mouse movement issues "almost but no dice" 1 Answer
Problem with Alt + Middle Click Drag for Camera (Windows) 3 Answers