- Home /
how to rotate a gameobject in a given direction and stop when it's done
So I have a gameobject (my player) which moves via a joystick. Without the rotating code below my player moves well and smooth, but after I put the rotating code below the gameobject rotates all the time (360 degrees) when I try to move it.
My aim is to rotate the player in a given direction and stop when it's done. I read that I should use RotateTowards but how can I do it when I have an angle. Or is there a better way to rotate it.
void Update()
{
// move
_rigidbody.MovePosition(transform.position + (transform.forward * leftController.GetTouchPosition.y * Time.deltaTime * speedMovements) +
(transform.right * leftController.GetTouchPosition.x * Time.deltaTime * speedMovements) );
//rotate
double rad = Mathf.Atan2(leftController.GetTouchPosition.y, leftController.GetTouchPosition.x); // In radians
double deg = rad * (180 / System.Math.PI);
transform.RotateAround(transform.position, Vector3.up , (float) deg *Time.deltaTime); //here it rotates all the time because of the frame
}
Answer by JohanesGroon · Aug 08, 2017 at 04:42 PM
public class joystick_script : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {
public virtual void OnPointerDown (PointerEventData ped)
{
Transform.rotation (0,0,deg);
}
I don't know if this will work just try it out... sorry for the uncertain answer
no unfortianally not.. I changed my rotating code to this.: Vector3 targetDir = new Vector3(leftController.GetTouchPosition.x,leftController.GetTouchPosition.y,0.0f); float step = Time.deltaTime; Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F); //Debug.DrawRay(transform.position, newDir, Color.red); transform.rotation = Quaternion.LookRotation(newDir);
but now the problem is that my object moves up and down and left to right but i only want that it moves left to right. do you know how to do it?