I am trying to create a unity C# script for a mouse controlled character movement system. Basically how games like Diablo work, one clicks somewhere in the game world, and the character moves to that location.
I had first tried this using the Vector3.MoveTowards method but realised that this ignored collision completely. I am now using a characterController component. I cast a ray unto the terrain to get a Vector3 position and use this to determine my movement.
The problem I am facing however is that the character does move towards the clicked point, colliding with objects along the way and sliding to the side until it is on a non colliding path again. the raycasthit seems to be accurate. but my character wont stop moving!
I even added a if clause before any movement command to check if the characters.transform.position is equal to the raycast hit position. this however did nothing. This is my code:
using UnityEngine;
using System.Collections;
public class MouseMoverComponent : MonoBehaviour {
private Vector3 direction;
private Vector3 movement;
private Vector3 destination;
private float velocity = 40f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//doMovement
if(gameObject.transform.position != destination){
GetComponent<CharacterController>().Move(movement);
}
//get raycast position on terrain
if(Input.GetMouseButtonDown(0)){
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 300.0f))
{
direction = hit.point - transform.position;
movement = direction.normalized * velocity * Time.deltaTime;
if (movement.magnitude > direction.magnitude) movement = direction;
transform.LookAt(hit.point);
destination = hit.point;
}
}
}
}
destination = gameObject.transform.position;
when a collision occurs. But, i'm not sure about the functionality you are looking to implement – Eissa