So im trying to make a top down rpg style wc3 kind of project. So i want my character to follow my mouse when i click on the ground, however i am having porblems with Raycast as i am a noobie.
Heres the code.
using UnityEngine;
using System.Collections;
public class ClickToMove : MonoBehaviour {
public Transform movepoint;
float turnSpeed = 10.0f;
float moveSpeed = 1;
private bool isMoving = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Debug.DrawRay(transform.position, Vector3.down);
if(Input.GetMouseButtonDown(0))
{
//Here i check if i click the left mousbutton and where i click it.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray,out hit)) {
print ("Your Cursor hit at " + hit.point + "!");
GameObject toKill = GameObject.FindGameObjectWithTag("MoveLocation");
GameObject.Destroy(toKill);
Instantiate (movepoint, new Vector3(hit.point.x,hit.point.y + 1,hit.point.z), transform.rotation);
isMoving = true;
}
}
if (isMoving == true){
GameObject toMove = GameObject.FindGameObjectWithTag("MoveLocation");
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(new Vector3(toMove.transform.position.x, toMove.transform.position.y,toMove.transform.position.z) - new Vector3(transform.position.x,transform.position.y,transform.position.z)), turnSpeed * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, new Vector3(toMove.transform.position.x, toMove.transform.position.y, toMove.transform.position.z) , moveSpeed * Time.deltaTime);
if (Vector3.Distance(transform.position,toMove.transform.position) <= 1) {
isMoving = false;
print("Im here.");
}
}
}
}
i attach this script to my player and i create a empty gameobject that is called movepoint and a plane with the tag MoveLocation. I think i might have messed up on those so im gonna provide some pictures.
In the album theres also the error i get when i left click.