Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Need to rotate an object towards mouse click

Discussion in 'Scripting' started by Ben555, Sep 16, 2020.

  1. Ben555

    Ben555

    Joined:
    May 22, 2019
    Posts:
    13

    void Start()
    {
    targetPosition = transform.position;
    plane = new Plane(Vector3.up, new Vector3(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))
    {
    transform.position += (targetPosition - transform.position).normalized * speed * Time.deltaTime;
    }
    else
    {
    transform.position = targetPosition;
    }
    }

    So far it moves towards mouse click, but I would like it to rotate first. I would think if I attach an empty (which represents the front of the Object) and then it rotates towards where the mouse was clicked. It also needs to stay at a height of y = 40 and rotate only on the y axis.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,760
    Mathf.Atan2() will give you the angular direction of a delta between two cartesian points.

    Mathf.Atan2() returns results in radians so be sure to multiply the result by Mathf.Rad2Deg to get it into degrees, if that is what you need.

    Mathf.MoveTowardsAngle() helps you move on a 0-360 basis from one heading to another, taking the shortest way to turn towards it.

    Also, please use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
  3. Ben555

    Ben555

    Joined:
    May 22, 2019
    Posts:
    13
    Ok thanks I'll try, and I will use code tags next time!