- Home /
Click to move
I need to make realistic human movement (3D) using mouse click.
Get mouse click point using
Raycast
.Smoothly
Slerp
toLookRotation
.Move
transform.forward
.
Everything works fine, except I have problem with circular movement (close radius).
Example If dont move
transform.forward
whileSlerp
toLookRotation
orMoveTowards
instead oftransform.forward
it will be spinning like whirligig on circular movement.Example If do move
transform.forward
while whileSlerp
toLookRotation
it will distort trajectory of straight direct movement.
Is there any solution to move circular realistic (not spin like whirligig) and move straight direct when needed (not distort trajectory)?
I need straight movement from first example and circular movement from second.
if (Input.GetMouseButtonDown(1))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hits = Physics.RaycastAll(ray);
foreach (RaycastHit hit in hits)
{
if (hit.transform.tag == "Ground")
{
DestinationPosition = new Vector3(hit.point.x, transform.position.y, hit.point.z);
DestinationRotation = Quaternion.LookRotation(DestinationPosition - transform.position);
break;
}
}
}
if (Vector3.Distance(transform.position, DestinationPosition) > 1)
{
transform.rotation = Quaternion.Slerp(transform.rotation, DestinationRotation, RotationSpeed * Time.deltaTime);
transform.position += transform.forward * MovementSpeed * Time.deltaTime;
//transform.position = Vector3.MoveTowards(transform.position, DestinationPosition, MovementSpeed * Time.deltaTime);
animation.CrossFade("run");
}
else
{
animation.CrossFade("idle");
}
Have you looked at the Unity navmesh system? That would probably be a lot easier than trying to code the same thing yourself, which is what you're doing.
Answer by BenKurdziel · Oct 04, 2014 at 05:37 AM
My suggestion for any click to move would be to look at Unity's navmesh system. From a performance standpoint, it's the most optimized and one of the easiest approaches.
If you'd like to look into this, here's some reference material and a quick set up I wrote in about 2 minutes. Good luck!
http://docs.unity3d.com/ScriptReference/NavMesh.html
1) "Window/Navigation"
2) Mark Objects you've clicked on that you'd like people to walked on as "Navigation Static"
3) Bake it when you're done.
4) Put a NavMeshAgent on anything you'd like to move.
5) Call: .SetDestination(hit.point);
Your answer
