- Home /
Rotating game object to movement direction
Hello, similar questions are asked but I still can not resolve mine. I am trying to rotate my game object to a mouse position but I think i have something wrong. I want to rotate my object only at Y-axis.
public class Drag : MonoBehaviour
{
private Vector3 offset;
private Vector3 movementDirection;
public Vector3 mousePosition;
public Camera cam;
void Update()
{
//smoothLookTowardDirectionOfMovement();
if (Input.GetMouseButton(0))
{
Plane plane = new Plane(Vector3.up, new Vector3(0, 18.4f, 0));
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance;
if (plane.Raycast(ray, out distance))
{
transform.position = ray.GetPoint(distance);
}
mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
calcuateNewMovementVector();
gameObject.transform.rotation = Quaternion.LookRotation(movementDirection);
}
}
void calcuateNewMovementVector()
{
movementDirection = new Vector3(0, mousePosition.y,0).normalized;
}
Comment
Answer by joemane22 · Feb 23, 2020 at 08:00 AM
Just pointing out, your movementDirection is always going to be the y unit vector. (0,1,0). Because you are only setting the mousePosition in the y component, when you normalize itit realizes there is only one component(y) that is utilized and sets it to zero.
You might want to use Mathf.Atan2(y, x)
here is the pseudo-code
pos = mousePos - position;
float direction = Mathf.Rad2Deg * Mathf.Atan2(pos.y, pos.x);
You may have to play around with the signs of the x and y when passing into the Atan2 function. You also may need to add or subtract 90 degrees. Just keep moving numbers around until you find the correct one.