how to rotate a mesh with GetMouseButton with specific rotation value
Hello there,
I'm really new to C# scripting (really new here :3) I'm trying to rotate a mesh with GetMouseButton and has a specific rotation value when i click on it.
My idea is i wan to click the mesh, and make it rotate at a specific value of -90 on the y-axis, and when i click again, i want it to return back the y-axis to 0.
here is my script:
using UnityEngine; using System.Collections;
public class playerscript : MonoBehaviour {
public float speed;
private Vector3 dir;
// Use this for initialization
void Start () {
dir = Vector3.zero;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton (0)) {
if (dir == Vector3.forward) {
dir = Vector3.left;
transform.Rotate (0, -90, 0);
} else {
dir = Vector3.forward;
transform.Rotate (0, 0, 0);
}
}
float amoutToMove = speed * Time.deltaTime;
transform.Translate (dir * amoutToMove);
}
}
The problem that i'm having is when i hold the mesh, it will rotate in full circle.. and i would like to prevent that haha.
The mesh will also move forward when i click the mesh.
Could anyone help me with this? I much appreciate your help :) Thank you
Answer by SmomoGame · Nov 29, 2016 at 04:14 PM
transform.Rotate is "Relative", means "Turn around some degree from CURRENT degree" not "Look at specific degree"
In your code, the mesh will rotate -90 first, then rotate 0 degree (nothing happen), and continue to rotate -90.
You may want to use transform.eulerAngles to set a specific angle constantly
Modify "transform.Rotate" to
transform.eulerAngles = new Vector3(0,-90f,0) ;
-90 or 0
Answer by Solhart · Nov 29, 2016 at 04:30 PM
It worked! thank you SmomoGame hahaha I'm really glad you replied haha
but i have a new problem now.. When i click, the mesh did turn at -90, but now the mesh is moving backwards instead of going left.
I'm sry, i'm rly a noob with this haha
transform.eulerAngles is "World" coordinate.
If you turn back with -90 degree, means your initial direction is not world's forward, So just add some offset to the value.
maybe 0 = your left , 90 = your forward (try yourself)
aaa ic.. no wonder hahaha orait2 ill give it a try, thx alot mate haha
*brofist from $$anonymous$$alaysia
Your answer
Follow this Question
Related Questions
Rotating on other axis 1 Answer
How to object rotate on a single axis towards another object? C# 2 Answers
Rotate an Object while moving forward using empty gameObject 0 Answers
How to rotate an object according to the camera's view? 1 Answer
how do I rotate an object without affecting later rotation? 0 Answers