Click to Move Mecanim C# script

I was searching about for a Click to Move example in C# that ran with Mecanim and actually worked, I couldn’t find one after much searching. So here is a basic one I made, debugged and live in a game… It’s basic for now.

Point and click raycasting
Terrain Gravity (Actually works and fixes issues with RigidBody)
Animation trigger on shared float with Mecanim
Transitions (Mecanim) from matching Raycasting position (Speed) and returns to 0 at point of destination.

using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Animator))]

public class CharControlAnim : MonoBehaviour {

    private Transform myTransform;				// this transform
	private Vector3 destinationPosition;		// The destination Point
	private float destinationDistance;			// The distance between myTransform and destinationPosition
    public float Speed;							// Speed at which the character moves
	public float Direction;                    // The Speed the character will move
    public float moveAnimSpeed;                // Float trigger for Float created in Mecanim (Use this to trigger transitions.
	public float animSpeed = 1.5f;      	  // Animation Speed
	public Animator anim;					  // Animator to Anim converter
	public int idleState = Animator.StringToHash("Base Layer.Idle"); // String to Hash conversion for Mecanim "Base Layer"
	public int runState = Animator.StringToHash("Base Layer.Run");  // String to Hash for Mecanim "Base Layer Run"
	private AnimatorStateInfo currentBaseState;			// a reference to the current state of the animator, used for base layer
	private Collider col; 
	
        
 
 
	void Start () {
	    
		Physics.gravity = new Vector3(0,-200f,0); // used In conjunction with RigidBody for better Gravity (Freeze Rotation X,Y,Z), set mass and use Gravity)
		anim = GetComponent<Animator>();
		idleState = Animator.StringToHash("Idle"); // Duplicate added due to Bug
	    runState = Animator.StringToHash("Run");
		myTransform = transform;							// sets myTransform to this GameObject.transform
		destinationPosition = myTransform.position;	
		                  // prevents myTransform reset
	}
 
	void FixedUpdate () {
 
		// keep track of the distance between this gameObject and destinationPosition		
		
		currentBaseState = anim.GetCurrentAnimatorStateInfo(0);
		
		destinationDistance = Vector3.Distance(destinationPosition, myTransform.position);
			    
				 // Set's speed in reference to distance
	
			if(destinationDistance < .5f){		
			Speed = 0;
		}
		else if(destinationDistance > .5f){			
			Speed = 8;
		
			//Below sends Floats to Mecanim, Raycast set's speed to X until destination is reached animation is played until speed drops
		} 
		 
		if (Speed > .5f){
		anim.SetFloat ("moveAnimSpeed", 2.0f);}
			
				else if (Speed < .5f){
		anim.SetFloat ("moveAnimSpeed", 0.0f);} // 
 
 
		// Moves the Player if the Left Mouse Button was clicked
		
		
		if (Input.GetMouseButtonDown(0) GUIUtility.hotControl ==0) {
 
			Plane playerPlane = new Plane(Vector3.up, myTransform.position);
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			float hitdist = 0.0f;
 
			if (playerPlane.Raycast(ray, out hitdist)) {
				Vector3 targetPoint = ray.GetPoint(hitdist);
				destinationPosition = ray.GetPoint(hitdist);
				Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
				myTransform.rotation = targetRotation;
			    
				
			}
	
				}	
		
	
		
 
		// Moves the player if the mouse button is hold down
		else if (Input.GetMouseButton(0) GUIUtility.hotControl ==0) {
 
			Plane playerPlane = new Plane(Vector3.up, myTransform.position);
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			float hitdist = 0.0f;
 
			if (playerPlane.Raycast(ray, out hitdist)) {
				Vector3 targetPoint = ray.GetPoint(hitdist);
				destinationPosition = ray.GetPoint(hitdist);
				Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
				myTransform.rotation = targetRotation;
			}
		//	myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, moveSpeed * Time.deltaTime);
		}
 
		// To prevent code from running if not needed
		if(destinationDistance > .5f){
			myTransform.position = Vector3.MoveTowards(myTransform.position, destinationPosition, Speed * Time.deltaTime);
		}
	}
}
1 Like

Just what I needed Thank you

This helped me out a great deal, thanks so much for posting it!

Could someone show me how the Animator Have too like for this? screenshot is enough :slight_smile:

Just attach the animator to the object (If it’s not already there), as there is a required type at the top of the script.

I’ll also mentioned this script was based on a rigidbody setup, if you’re using it in an RPG context don’t forget to to freeze the correct axis to get it working correctly. Or you may find it doing a homer simpson floor spin and other weird issues may arise…

I used this script for a hack and slash concept demo I did a while back ago, feel free to ask questions but as I don’t use point and click any more so I can’t send you screenshots.

I got a ton of “unexpected symbol” and a parsing error in the console. I’m not at all familiar with scripting in JS much less C#. Will this work with script-driven root motion on a mecanim setup?

Hey thanks for that script! Helped me a lot!
But doesnt work perfect on uneven terrain :confused: any idea how to run this with NavMesh? if i use “x.SetDestination (hitdist);” it doesnt work with the “speed” variable, have no idea how to do this :confused:

Jesus Christ, all available information is for Unity 4.x . Is there nothing for 5.x??? Even the official crap doesn’t work a lot of times.

There are lots of tutorials in Unity 5, also if you need help with stuff just ask here on the forums. Another option is to find the simple differences between 4 and 5 http://docs.unity3d.com/Manual/UpgradeGuide5.html.