0
\$\begingroup\$

I'm trying to get an object to smoothly rotate towards a clicked point in my terrain.

However, my code only yields jittery movements in the other direction.

Any help will be greatly appreciated.

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    public float rotationSpeed = 5.0f;

    private Quaternion _lookRotation;
    private Vector3 _direction;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.tag == "Ground")
                {

                    Vector3 looker = new Vector3(hit.point.x, hit.point.y, 0); //get x and y point from ray cast.

                    _direction = (looker - transform.position).normalized;

                    _lookRotation = Quaternion.LookRotation(_direction);

                    transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * rotationSpeed);

                }
            }
          }


    }
}
\$\endgroup\$
1
\$\begingroup\$
Vector3 targetDirection;
float rotationSpeed;

void Start() {
    targetDirection = this.transform.forward;
}

void Update() {
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.tag == "Ground")
            {
                Vector3 looker = new Vector3(hit.point.x, hit.point.y, hit.point.z); //get x and y point from ray cast.
                targetDirection = (looker - transform.position).normalized;
            }
        }
    }

    this.transform.forward = Vector3.Lerp(this.transform.forward, targetDirection, Time.deltaTime * rotationSpeed);
}

This will cause the Object this script is attached to to constantly rotate towards the TargetDirection. Upon MouseClick you will update TargetDirection with the new point of interest and the GameObject will rotate as needed to face it. This is assuming "transform.forward" points along the correct axis of your Mesh to represent its forward as well in your game. If not just change that line of code to suit your model.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.