简体   繁体   中英

Rotate object to face mouse direction

I have a method that will rotate my object to the point my mouse just clicked on. However, my object only rotates as long as my mouse button is held down.

My main rotation method is this:

void RotateShip ()
{
    Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    Debug.Log (Input.mousePosition.ToString ());
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {
        Vector3 targetPoint = ray.GetPoint (hitdist);
        Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);
        transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
    }
}

I call this method inside the FixedUpdate method and I've wrapped it inside the following if statement:

void FixedUpdate ()
    {
        // Generate a plane that intersects the transform's position with an upwards normal.


        // Generate a ray from the cursor position
        if (Input.GetMouseButton (0)) 
        {

            RotateShip ();

        }
    }

However, the object will still only rotate as long as my mouse button is held down. I want my object to continue to rotate to the point my mouse just clicked until it reaches that point.

How can I amend my code properly?

It's only rotating while your mouse is down because that's the only time you tell it to rotate. In your FixedUpdate (which Imtiaj rightfully pointed out should be Update ), you're only calling RotateShip() while Input.GetMouseButton(0) is true. That means that you only rotate your ship while the button is pressed.

What you should do is take that mouse event and use it to set a target, then continuously rotate toward that target. For instance,

void Update() {    
    if (Input.GetMouseButtonDown (0)) //we only want to begin this process on the initial click, as Imtiaj noted
    {

        ChangeRotationTarget();

    }
    Quaternion targetRotation = Quaternion.LookRotation (this.targetPoint - transform.position);
    transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
}


void ChangeRotationTarget()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    Plane playerPlane = new Plane (Vector3.up, transform.position);

    float hitdist = 0.0f;

    if (playerPlane.Raycast (ray, out hitdist))
    {
        this.targetPoint = ray.GetPoint (hitdist);
    }
}

So now instead of only doing the rotation while MouseButton(0) is down, we do the rotation continuously in the update and instead only set the target point when we click the mouse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM