- Home /
How to rotate object back and forth on input hold?
I tried mathf.PingPong but it seems to be always active/rotating behind the scene even when i don't press anything.
I need it to rotate back and forth when i hold the button, return to it's starting rotation on release, and start rotate again from the starting rotation when i hold the button.
This is the code that i have now.
using UnityEngine;
using System.Collections;
public class HoldToRotate : MonoBehaviour
{
private Quaternion startingRotation;
public float rot = 180;
public float rotSpeed = 10;
void Start()
{
startingRotation = transform.rotation;
}
void Update()
{
if (Input.GetKey(KeyCode.F))
PingPongRotation();
else if (Input.GetKeyUp(KeyCode.F))
transform.rotation = startingRotation;
}
void PingPongRotation()
{
transform.localEulerAngles = new Vector3(-Mathf.PingPong(Time.time * rotSpeed, rot), 0,0);
}
}
Answer by KuR5 · Jun 21, 2016 at 09:29 AM
Hi @Babars,
That problem is due to Time.time in Mathf.PingPong().
So find solution below :
float _tempTime = 0;
void PingPongRotation ()
{
_tempTime += Time.deltaTime;
transform.localEulerAngles = new Vector3 (-Mathf.PingPong (_tempTime * rotSpeed, rot), 0, 0);
}
Thanks. It worked perfectly after i add _tempTime = 0f; in Input.Get$$anonymous$$eyUp.
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Object rotation using Mathf.Atan2 0 Answers
C# Mathf.PingPong Rotate Back and Forth 2 Answers
Distribute terrain in zones 3 Answers
problem after rotate an object 0 Answers