- Home /
Rotate object by clicking on it with animation
Hello there! I searched for days now and can't seem to find what I am really searching for... I want to roate an object in Unity 90 degrees, by clicking on it. And I did and it works, the problem is that I want to "show" the movement to the player, and not have the object be 0 degrees on frame 1 and 90 degrees on frame 2. I want the object to gradually rotate to 90 degrees. I want to "animate" the movement, although without using animator on the object.
I used Time.deltaTime and it didn't rotate gradually(maybe I am using it somewhat wrong?)
Any help would be highly appreciated!
Heres with what I am working with (code)
private void Update()
{
if (!completion) //checks weather the picture is completed, if not, it lets you click
{
if (Input.GetMouseButtonDown(0)) // checks weather you hit the left mouse click
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f)) // checks if it hits the object
{
if (hit.transform != null)
{
PrintName(hit.transform.gameObject);
hit.transform.Rotate(0f, 0f, 90f); // rotates the clicked tile 90 degrees
//hit.transform.Rotate(0f, 0f, 90f * (Time.deltaTime * rotateSpeed)); //doesn't show the movement
}
}
}
Answer by WarmedxMints · Sep 26, 2019 at 09:44 AM
You can set a target rotation and lerp to it.
using UnityEngine;
public class RotateOnClick : MonoBehaviour
{
public Vector3 RotateStep = new Vector3(0, 90, 0);
public float RotateSpeed = 5f;
private Quaternion _targetRot = Quaternion.identity;
private void Update()
{
transform.rotation = Quaternion.Lerp(transform.rotation, _targetRot, RotateSpeed * Time.deltaTime);
}
public void OnMouseDown()
{
_targetRot *= Quaternion.Euler(RotateStep);
}
}
Thank you for the reply, unfortunately it didn't work, there was no "animation", it just "snapped" 90 degrees.
Then you did something wrong, the code works perfectly. Did you remember to remove your code?
Your answer
Follow this Question
Related Questions
Why is the rotation missing when I animate? 1 Answer
How to rotate an object with animation? 0 Answers
Why one of object's animation has global rotation data, and another has local rotation data? 0 Answers
How can you rotate the object both through animaton and through code in the same time? 1 Answer
Wonky Camera Behaviours 0 Answers