- Home /
Mouse Click to Move and Mesh Colliders
Hey all - I have a character using the locomotion system (I haven't moved over to Mecanim yet) and I have him walking around with a mouse to click script (I was having issues with the Locomotion ClickController script that was posted online). He's animated and all of that stuff, but one thing that I'm having issue with is that he seems to ignore mesh colliders. If I click on a wall (that I built with ProBuilder...so it automatically generates a collider) I would expect him to stop when he reaches it, but he passes straight through. I threw a different character controller on the player and he does stop when I run him against the wall, so I know it's the mouse click to move script...but I just don't know what I should add to it to make sure takes colliders into account (like it just stops it's transform if the character is blocked by a collider). Here's the code (pulled from online and did some minor tweaks): // Click To Move script // Moves the object towards the mouse position on left mouse click
var smooth:float = 2; // Determines how quickly object moves towards position
public var targetPosition:Vector3;
public var distanceThreshold:float = 0.1f;
private var hasTarget:boolean = false;
private var controller: CharacterController;
function Start(){
controller = GetComponent(CharacterController);
}
function Update () {
if(Input.GetKeyUp(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;
hasTarget = true;
}
}
if(hasTarget == true)
{
transform.position = Vector3.MoveTowards (transform.position, targetPosition, Time.deltaTime * smooth);
if (Vector3.Distance(transform.position, targetPosition) <= distanceThreshold)
{
hasTarget = false;
}
}
}