0

Given a top-down persepective and lets say I know the angle I want to look at, how do I make a gameobject look into that angle? I currently have code like this:

if (directionX != 0 && directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX / 2, 0, directionZ / 2));
}
else if (directionX != 0 || directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX, 0, directionZ));
}

which allows me to move look into 8-directions. I am now looking to make it so I can look in any angle and I've got the angle using:

var angle = Mathf.Atan2(directionZ, directionX) * Mathf.Rad2Deg;

but I don't know how to use it to make my object look into that angle.

g_b
  • 369
  • 4
  • 12
  • what you exactly looking for? for looking at object you can use transform.lookat with z equal to zero – virtouso Oct 19 '19 at 09:05
  • 1
    The code you've shown works for any angle. The if branch does nothing useful so you can skip that part. There's no need to compute an angle from the direction vector when you can just use the vector directly as you're doing. If you're not getting the results you want from this, then it will be down to how you've created your directionX / Z values, so you should show us that part, along with a detailed description of the symptoms you need to solve. – DMGregory Oct 19 '19 at 12:33
  • @DMGregory: I think you may be right, maybe how I'm getting my X and Z values is the thing that is wrong. Currently, it can only have 2 values: 1 and -1. I think that's why my rotation is limited to 8 angles. The reason is I have a custom input manager and I was trying to make this work with the values my input manager is outputting when the input manager may be the problem. I'll try it out when I get home and post the results. Thanks for mentioning that. – g_b Oct 21 '19 at 00:38

1 Answers1

1

Store the position into a Vector3 and you can use that to LookAt

Vector3 lookAtObj

        Quaternion newRotation = Quaternion.LookRotation(lookAtObj);
        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, 1);

If you want to avoid Lerp or Slerp then I would suggest something like LookAt

    transform.LookAt(transform.position + lookAtObj.transform.rotation * Vector3.forward,
    lookAtObj.transform.rotation * Vector3.up);
Justin Markwell
  • 2,182
  • 1
  • 13
  • 16