Probably this has been answered in some kind of way but i’m having too much trouble finding it.
So the problem is, let’s say for example i have ObjectA and I want to it’s position to be the same as the mouses while still being on ground height (for the time being let’s say y = 0 ). So if i’m pointing with my mouse on a location that is (1, 1, 0) i want that object to have the same coordinates. This probably ain’t done with the ScreenToWorldPoint but rather with the raycast but i’m having troubles with it :S. Could anyone help me go about this ?
Ok, so basically, you need to Raycast on the Plane and then go there.
I did it with a Navmesh and a NavMeshAgent, so it’s like any TopDown games, so you can click and it finds a Path.
private Transform myTransform; // this transform
private Vector3 targetPosition; // The destination Point
private float targetDistance; //Distance between Char and Poit of Ray
private RaycastHit rayHit; //Stores the Information of the Raycasthit
private Vector3 eP;
private float rangeDistance;
void Start () {
myTransform = transform;
targetPosition = myTransform.position;
rangeDistance = 0.5f;
}
void Update () {
// Moves the Player if the Right Mouse Button was clicked
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(1) GUIUtility.hotControl == 0) {
Plane playerPlane = new Plane(Vector3.up, myTransform.position);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist)) {
Vector3 targetPoint = ray.GetPoint(hitdist);
targetPosition = ray.GetPoint(hitdist);
rangeDistance = 0.5f;
}
// keep track of the distance between this gameObject and targetPosition
targetDistance = Vector3.Distance(targetPosition, myTransform.position);
// Set the Movement according to the State
if(targetDistance > rangeDistance){
GetComponent<NavMeshAgent>().destination = targetPosition;
}else{
targetPosition = transform.position;
GetComponent<NavMeshAgent>().destination = targetPosition;
}
}
I think the script is self explaining, if you need any Help with it, simply comment.
For the NavMesh, quickly look it up on Youtube, it’s really not difficult.
As a Reminder: Think about each operation which is done here and do not copy paste the script. Try to learn from it.
Greez Joker_54
Yeh it actually isn’t that difficult, I guess I had a few problems understanding how to get the raycast to work as I wanted.
Thanks again for helping me out with this, really appreciate it.