- Home /
How to rotate a cylinder on the mouse position ?
Hello
I'm trying to rotate a cylinder but I have some issues. I want that my cylinder rotate in the direction of my mouse position .
I tried some math algorythm like this :
Vector2 _point;
_point = new Vector2(transform.position.x, \
this.renderer.bounds.size.y/2 + transform.position.y);
Vector3 mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
Vector2 AB = new Vector2(_point.x - transform.position.x, _point.y - \
transform.position.y);
Vector2 AC = new Vector2(mousePos.x - transform.position.x, mousePos.y - \
transform.position.y);
Vector2 BC = new Vector2(mousePos.x - _point.x, mousePos.y - _point.y);
float dAB = Mathf.Sqrt(Mathf.Pow(AB.x,2) + Mathf.Pow(AB.y,2));
float dAC = Mathf.Sqrt(Mathf.Pow(AC.x, 2) + Mathf.Pow(AC.y,2));
float dBC = Mathf.Sqrt(Mathf.Pow(BC.x, 2) + Mathf.Pow(BC.y,2));
float toCos = ((AB.x * AC.x) + (AB.y * AC.y))/(dAB *dAC);
float _angle = Mathf.Acos(toCos) * Mathf.Rad2Deg;
this.Rotate(0,0,_angle);
_point = new Vector2(mousePos.x, mousePos.y);
It seems to work with the first click but not after. Is there something wrong with my math algorythm ? Or it with my use of unity object ?
Answer by Cherno · Nov 08, 2013 at 02:23 PM
You could just store the Vector3 the mouse is pointing at (by using RayCast) and then use Transform.LookAt.
http://docs.unity3d.com/Documentation/ScriptReference/Transform.LookAt.html
but that will rorate whole cilinder not just X axis, ...
I was doing something like that, ...
and I won't do much recoding just copy paste learn what you can, ...
public void DontLookAtYF(Vector3 Point){
Vector3 Temp = transform.localEulerAngles;
transform.LookAt(Point);
Temp.y = transform.localEulerAngles.y;
transform.localEulerAngles = Temp;
}
thanks to @Cherno I get the idea what questioner exactly wants, ...
Thank you, it works fine . It's been two days that i'm on it .