I’m trying to make an RTS, so I need to be able to right-click to where I want my unit to go. So far, I’ve gotten it so that I can select a unit with a script in the main camera, and then click to teleport the unit to a point. I don’t want the unit to teleport, but instead to move towards the point.
Here’s my code for the movement:
void Update(){
if (Input.GetButtonDown ("Fire2") && target.tag == "Unit") {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
destination = hit.point;
target.rigidbody.MovePosition(destination);
}
}
}
Nevermind, I fixed it. First I converted the .MovePosition to .MoveTowards, but it still jumped around. It turns out that the code was only executing during the frame in which you right-clicked, so I moved it out of the if statement it was in and adjusted the code accordingly.
Here’s the entire script, which is placed into the main camera. The way I set it up, you always need to have a target selected, so to prevent errors you need to put a gameObject with a rigidbody into “bTarg”.