- Home /
Want to move object slowly to where the mouse clicks?
I can move it instantly so far, and I also need to maintain level height (y=40)
if (Input.GetMouseButtonDown(0)) { Plane plane = new Plane(Vector3.up, new Vector3(0, 40, 0)); Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out float distance)) { transform.position = ray.GetPoint(distance); } }
Answer by unity_ek98vnTRplGj8Q · Sep 08, 2020 at 03:45 PM
Just set a target position instead and move your object toward this position every frame
private Vector3 targetPosition;
public float speed;
private float height = 40;
private Plane plane;
void Start() {
targetPosition = transform.position;
plane = new Plane(Vector3.up, new Vector(0,height,0));
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (plane.Raycast (ray, out float distance)) {
targetPosition = ray.GetPoint (distance);
}
}
float distanceToDestination = Vector3.Distance(transform.position, targetPosition);
if(distanceToDestination > (Time.deltaTime * speed)){ //We won't reach destination this frame
//Move toward the destination
transform.position += (targetPosition - transform.position).normalized * speed * Time.deltaTime;
} else { //We will reach destination this frame
transform.position = targetPosition;
}
}
Awesome this worked, thanks! Any chance you could help with the rotation? I used the Scripting API to get started:
Vector3 targetDirection = Input.mousePosition - transform.position;
float singleStep = speed * Time.deltaTime;
Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);
Debug.DrawRay(transform.position, newDirection, Color.red);
transform.rotation = Quaternion.LookRotation(newDirection);
However at the moment it kind of just rotates in any direction where the mouse is. I want it to only rotate in the Y Axis. I tried to freeze position for X and Z but it didn't work.