- Home /
How to rotate a 2D object (ex. log) with rigidbody2D based on touchPosition
Hello Guys. I need some help building a rotation algorithm in C#(Unity). I have a log as you can see in the image that I want to rotate based on the touch of the player. So far what I have tried , but I am not really satisfied with, is: I calculate the dot product of the tangent vector to the log and the deltaTouchPosition (transform.right * touchPosition) and then distance of the touch and the Pivot Point. So based on rotational physics , angular velocity should be ω = v / r ; where v is the dotProduct / Time.delta time and r is the distance I mentioned above. I am currently using the 2D rigid body system of Unity so my code looks like. float v = Vector2.Dot(transform.right,touch.deltaPosition)/Time.deltaTime; float r = Vector2.Distance(transform.position,Camera.main.WorldtoScreenPoint(touch.position)); rigidbody2D.angularvelocity = v / r;
Any Ideas are welcome. Thanks in advance http://i.imgur.com/9VX833r.png
Answer by robertbu · Sep 18, 2014 at 08:31 AM
I assume the '+' in the center is the pivot point of your log. Here is a bit of code that will rotate the using the mouse. I leave converting it to touch for you to do:
#pragma strict
private var rightSide = true;
private var deltaAngle : float;
function OnMouseDown() {
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = transform.position.z;
var localPos = transform.InverseTransformPoint(pos);
rightSide = localPos.x > 0.0;
var dir = pos - transform.position;
var mouseAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
if (rightSide) {
dir = transform.right;
var objAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
deltaAngle = mouseAngle - objAngle;
}
else {
dir = -transform.right;
objAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
}
deltaAngle = mouseAngle - objAngle;
}
function OnMouseDrag() {
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = transform.position.z;
var dir = pos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - deltaAngle;
if (rightSide) {
rigidbody2D.MoveRotation(angle);
}
else {
rigidbody2D.MoveRotation(angle + 180.0);
}
}